Are there any problems associated with
vector< vector<int> > v(m, vector<int>(n));
Is it safer to write:
vector< vector<int> > v(m);
for (size_t i=0; i<m; i++)
v[i].resize(n);
Are there any problems associated with
vector< vector<int> > v(m, vector<int>(n));
Is it safer to write:
vector< vector<int> > v(m);
for (size_t i=0; i<m; i++)
v[i].resize(n);
Yes, it is safer, especially if the second dimension, n
was very large. The resizing approach would be preferred in memory limited, embedded systems programming. Take the example of
vector< vector<int> > v(2, vector<int>(1'000'000));
Constructing the 2D vector of vectors would (for most compilers) require an additional 4'000'000
bytes (32 bit ints) compared to the resizing approach as it would create a vector of 1,000,000
needed to initialize the vectors. This is required because the vector<int>(1'000'000)
must be constructed. It is then used to initialize each of the m
row vectors. After execution it is destroyed so the increased memory requirement is short lived. Thus, I would prefer the second approach which does not require construction of an initializing vector.
That said, I quite agree with the point that a vector of vectors is a particularly bad approach to creating dynamic, 2D vectors unless each row is to have variable numbers of columns.
See my answer here which shows a short, efficient, class that can be used for 2D dynamic vectors. Statically declared 2-D array C++ as data member of a class