You do not need to call resize() when using push_back(); it will automatically extend the vector if necessary by reallocating it. You only need to call resize if you want to make the vector smaller, or if you want to add default constructed elements to the end.
|
void resize ( size_type sz, T c = T() );
|
You can give it an initial value to set the elements to, but if you leave it out, it just uses the default constructor. So in the above example, you do have to resize row if you want to go through and set the values using the index operator. Resize will go through and default initialize all elements of the vector though, and then you go through a second time and reset the values. It is better to call reserve to have the vector reserve sufficient space, but not do any initialization, and then go through and push_back the values. Even if you reserve space, it is an error to access anything outside of size, so if you have a vector with 5 elements, and you call reserve(10), you can still only access the 5 elements. To access more, you have to push_back, insert, or call resize.
Also, when you push_back a vector onto another vector, you are passing it by const reference, so unless the compiler can optimize it out, you are going to copy the entire vector, probably unnecessarily. You can push_back an empty vector, and then add the values to it to avoid the possibility of this.
1 2
|
I.push_back(vector<int>());
I[I.size()-1].push_back(5); // push 5 onto the last vector of integers in I.
|
On last thing: vector is a general purpose container. You may want to look at valarray for a container specifically meant to hold arithmetic types. Note that functions with the same name in valarray and vector do not necessarily do the same thing. Resize for example, will always wipe out any existing content for a valarray.
http://www.cplusplus.com/reference/std/valarray/valarray/
For multiple dimensions, you would probably want to use
vector<valarray<double> >
for example.