3
votes

Consider a two-dimensional vector with integers, but initially only with one element:

std::vector< std::vector <int> > vec( 1, std::vector<int>( 1, 0 ) );

Now I want to make the vector in both dimensions larger, so that the vector results always in a m x m matrix.

Will the following two commands do that:

vec.push_back( std::vector<int> );
vec[0].push_back( 0 );

or will just the first row and respectively the first column increase by an element?

3
It is just a vector which contains other vectors. So if you figure out how a vector works, you have your answer. - juanchopanza
If you want a dynamic, rectangular, multidimensional array, use a class which is made for that. e.g. something from Boost.MultiArray. A vector of vectors is a poor substitute. - Benjamin Lindley

3 Answers

1
votes

Only the first row will enlarge. The fact the vectors are all grouped together doesn't make them enlarge together.

1
votes

If you are creating a vector of vectors, you will need to increase every row if you want the width of every row to increase....

1
votes

A vector is a single dimensional container - the details of the contents are abstracted. That means, vector is supposed to know nothing about it's contents.

std::vector< TYPE >

Coincidentally, this means that you can use a sub-container that also overloads operator[], but don't mistake that for vector itself supporting [][].

std::vector< std::map< std::string, std::string > > foo;
foo[1]["hello"];

is basically

std::map& fooMap = foo[1];
fooMap["hello"];

There's no special case for vector