Re: Append values to a vector?
Francogrex wrote:
Hello, I am new to C++, have some knowledge of programming in
splus(statistics). I am trying to append values output by a loop (code
below) into a vector (by appending value), that I can eventually
export to a text file. The only way I could do this is output one
value at a time which doesn't seem elegant because the vector named
"input" is not stored in the workspace. How can I have a vector that
is saved in the workspace and that I can output it into a text in one
time? Thanks
// Program to generate random numbers
#include <time.h>
#include "randomc.h"
#include "mersenne.cpp"
#include "userintf.cpp"
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
int32 seed = (int32)time(0); // random seed
// choose one of the random number generators:
CRandomMersenne rg(seed); // make instance of random
number generator
// or:
// CRandomMother rg(seed); // make instance of random
number generator
int i; // loop counter
double r; // random number
int32 ir; // random integer number
double sum=0;
vector<double>input(1000);
std::ofstream os("text_file.txt");
// make random floating point numbers in interval from 0 to 1:
printf("\n\nRandom floating point numbers in interval from 0 to
1:\n");
for (i=0; i<1000; i++) {
r = rg.Random();
sum=sum+r;
input[i]=r;
cout << input [i]<< endl;
os << input[i]<< endl;
}
system("PAUSE");
return 0;
}
I don't quite understand what you are looking for. What is a workspace?
Here is a version that accomplishes pretty much the same thing without
any explicit looping. Probably the whole generate_n nonsense is
overkill, but feel free to pick and choose the parts that apply to your
question:
#include "randomc.h"
#include "mersenne.cpp"
#include "userintf.cpp"
#include <iterator>
#include <algorithm>
#include <numeric>
#include <vector>
#include <iostream>
#include <fstream>
#include <ctime>
const std::size_t N = 1000;
class RandomGenerator
{
public:
RandomGenerator(CRandomMersenne & rg)
: prg_(&rg)
{}
double operator()()
{
return prg_->Random();
}
private:
CRandomMersenne * prg_;
};
int main()
{
CRandomMersenne rg(std::time(0));
// Generate input vector.
std::vector<double> input;
input.reserve(N);
std::generate_n(std::back_inserter(input), N,
RandomGenerator(rg));
// Compute the sum.
double sum = std::accumulate(input.begin(), input.end(), 0.);
// Write generated values to file.
std::ofstream os("text_file.txt");
std::copy(input.begin(), input.end(),
std::ostream_iterator<double>(os, " "));
// Write generated values to stdout.
std::copy(input.begin(), input.end(),
std::ostream_iterator<double>(std::cout, " "));
}
--
Alan Johnson