Append values to a vector?

F

Francogrex

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::eek:fstream 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=r;
cout << input << endl;
os << input<< endl;
}
system("PAUSE");
return 0;
}
 
A

Alan Johnson

Francogrex said:
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::eek:fstream 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=r;
cout << input << endl;
os << input<< 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::eek:fstream os("text_file.txt");
std::copy(input.begin(), input.end(),
std::eek:stream_iterator<double>(os, " "));

// Write generated values to stdout.
std::copy(input.begin(), input.end(),
std::eek:stream_iterator<double>(std::cout, " "));
}
 
F

Francogrex

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

Hello, thanks for the code. By workspace I meant being able to reuse
the vector I created (called 'input') as a vector elsewhere in the
function (say in other subfunctions) as a vector. For example in S+
when I create a vector x= c(10,14,12,16,31) of 5 real numbers, then I
would be able to do vector manipulations on it such as x/2 would
equal= c(5, 7, 6, 8, 15.5)... But I don't know if C++ is essentially a
"vector friendly" language.
 
L

Lionel B

Hello, thanks for the code. By workspace I meant being able to reuse the
vector I created (called 'input') as a vector elsewhere in the function
(say in other subfunctions) as a vector.

You can pass your vector 'input' as a *parameter* to a function.

I'm not familiar with S+, but if it's anything like Matlab (which I know
something of) then I suspect that the nearest equivalent in C++ to an S+
variable is probably a `global variable'. But in C++ one is encouraged to
avoid using global variables wherever possible - it goes somewhat against
various programming paradigms that C++ supports/encourages.

Note too that C++ doesn't have `subfunctions', although functions in C++
can certainly call other functions (maybe we have a terminology clash
here).
For example in S+ when I create
a vector x= c(10,14,12,16,31) of 5 real numbers, then I would be able to
do vector manipulations on it such as x/2 would equal= c(5, 7, 6, 8,
15.5)...

That is a different matter entirely...
But I don't know if C++ is essentially a "vector friendly" language.

Hmm, I'd say not directly... the C++ std::vector class essentially has
rather limited support for numerical vector manipulation. There is a
class std::valarray which was originally conceived of as a sort of more
numerically-friendly vector, but it has "issues" and is not popular.

That having been said, there are plenty of 3rd party vector/matrix
libraries geared towards numerical manipulation, some of which may even
support comparable semantics to the vectors and matrices with which you
will be familiar.

C++ is an immensely rich and flexible language, but - compared with some
other languages - possibly has less functionality `built in'. So the
answer to questions such as "Is C++ XYZ-friendly" tend to be answered by
"Not directly, but someone has written an XYZ-friendly library for C++".
 
A

Alan Johnson

Francogrex said:
Hello, thanks for the code. By workspace I meant being able to reuse
the vector I created (called 'input') as a vector elsewhere in the
function (say in other subfunctions) as a vector. For example in S+
when I create a vector x= c(10,14,12,16,31) of 5 real numbers, then I
would be able to do vector manipulations on it such as x/2 would
equal= c(5, 7, 6, 8, 15.5)... But I don't know if C++ is essentially a
"vector friendly" language.

In C++ a "vector" is just a container of things of the same type that
are stored in contiguous memory. While the name is accurate, it is
misleading to people who expect to manipulate it like the "vector" in
other languages (especially math targeted languages).

You give a pretty good example of something that won't work for a
std::vector. That is:
std::vector<double> v2 = v1/2; // incorrect, won't work

You can apply C++ standard algorithms to vectors (or any container) to
achieve the same result. for_each and transform are popular. For
example, if you have a function f:
double f(double x) { return x/2.; }

You could apply that function to every member of a vector, storing the
results in another vector:
std::vector<double> v2;
std::transform(v1.begin(), v1.end,
std::back_inserter(v2), f);

Obviously this doesn't have the same elegance as "v1/2", as the C++
vector is more of a general purpose tool. You can combine it with other
tools (operator overloading, for example) to create what you are looking
for, and I'm sure there are C++ math libraries available that do just
that. Honestly, though, in the spirit of choosing the right tool for
the problem, I would choose Matlab/Maple/S+ if I needed to do that sort
of operation a lot.
 
F

Francogrex

Obviously this doesn't have the same elegance as "v1/2", as the C++
vector is more of a general purpose tool.  You can combine it with other
tools (operator overloading, for example) to create what you are looking
for, and I'm sure there are C++ math libraries available that do just
that.  Honestly, though, in the spirit of choosing the right tool for
the problem, I would choose Matlab/Maple/S+ if I needed to do that sort
of operation a lot.

Hi, yes I agree with you, but the reasons I wanted to learn C was that
I was told I could get a better understanding of the functioning of S
+, since the S language is not a primitive language like C++ (actually
S is build in part by C++ and Fortran). So getting to the source was
like a sort of trying to specialize. And the second reason was that I
needed to write protected programs where users couldn't get to and
modify the source code unless they request (the source code would be
given freely but upon request and this is not for commercial but for
regulatory reasons), so i thought better to compile exe programs
written in C++. Thanks for insight.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,016
Latest member
TatianaCha

Latest Threads

Top