Resizing nested C++ STL vectors
“Multidimensional” vectors in C++ do not behave like matrices (or higher-order equivalents). Something like:
vector< vector<double> > foo(100, vector<double>(20, 0.0));
will not lay out 100*20 doubles contiguously in memory. Only the bookkeeping info for 100 vector’s will be laid out contiguously — each vector will store its actual data in its own location on the heap. Thus, each vector can have its own size.
This can lead to hard-to-catch bugs:
foo.resize(300, vector<double>(30, 1.0));
will leave the first 100 vector’s with size 20, filled with 0.0 values, while the new 200 vector’s will have size 30, filled with 1.0 values.
This was originally published here:
https://calvinmccarter.wordpress.com/2015/05/19/resizing-nested-c-stl-vectors/