filling a vector

Hello,

I need to create a vector, and fill it with N many elements. But these elements inside the vector should be incremented, based on another variable, say eta=0.25. [So I cant use ++i operator] That is eta * N many elements. I'm pretty new to c++, I'd appreciate any hints you provide.
Something like this...?

1
2
3
4
5
6
7
8
std::vector<double> myVec;

const unsigned int MAX_ELEMS = 10;

for( double i = 0.0; myVec.size() < MAX_ELEMS; i += 0.25 )
{
   myVec.push_back( i );
}


That adds 0.25 to each new element of the vector. Unless you mean add something to the next element based on the last one?
Last edited on
Thanks a lot, it works! It helps me fill it with values that I want. Here is my piece of code, could you comment on the last part, if you have the time?


#include <iostream>
#include <vector>
using namespace std;

int main ()
{
const int N = 16 * 2;
double eta = 0.25;
vector<double> myvector;
const double MAX_ELEMS = N * eta;

for (double i = 0.0; myvector.size() < MAX_ELEMS; i += eta)
{
myvector.push_back(i);
}


cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); i++)
cout << ' ' << myvector.at(i);
cout << '\n';

return 0;
}

why do I need to use unsigned i = 0 in my for statement? and what does myvector.size() exactly do? does it take an argument inside its brackets?
Strictly speaking, you don't need unsigned i. You could use int i but since you're not working with negative numbers you might as well use unsigned - you have a higher upper limit that way.

The size() function of a vector returns exactly that; it's size. That's how many elements are stored in it. Check out the vector reference on this site.

You seem to have quite a convoluted way of setting your MAX_ELEMS to 8. Is there any reason for that?
Thanks again. Yes, in fact, this is just a vector I defined as part of a larger formula I need to implement. So, I need to define MAX_ELEMS in terms of N and eta.

I already looked at the <vector> part of the site. But I couldn't find vector operations in there, that is, I also need a subtraction and multiplication to be implemented with this vector. Could you provide a link maybe?

Thank you very much
All of the member functions are at the bottom of this page: http://www.cplusplus.com/reference/vector/vector/
Topic archived. No new replies allowed.