A std::vector<T>
has the property of storing its elements continuously in memory. But what about a std::vector<std::vector<T>>
? The elements within an individual std::vector<T>
are continuous, but are the vectors themselves continuous in memory (that is, the whole data kept in the outer vector would be one memory block)? Would not this imply, that if I resize one of the inner vectors I would have to copy (or move) many objects to preserve continuity?
And what about a std::array<std::array<T,N>,N>
? Here I would assume memory continuity just as for T[N][N]
A std::vector<T>
internally stores a pointer to dynamically allocated memory. So while the elements of a single std::vector<T>
will be continuous in memory there is no relationship to any pointers that those elements store themselves.
Therefore a std::vector<std::vector<T>>
will not have the elements of the "inner vectors" stored continuously in relation to each other. It would also be impossible for a resize of one of those "inner vectors" to affect the others, since at the point where the resize happens there is no information about any relationship to other std::vector<T>
objects.
On the other hand a std::array
is a (thin) wrapper around a C-style array and uses neither dynamic allocation nor is resizable, so a std::array<std::array<T,N>,N>
will have the same memory layout as a T[N][N]
array.