I know that std::vector<T>
internally stores it's data contiguously (unless it is std::vector<bool>
) both in the old C++03
standard and the new C++11
.
Nice stackoverflow questions that deal with this and quote the standard: answer, answer.
What about the data inside nested vectors std::vector <std::vector <T> >
? How is that stored?
If every internal vector needs to store it's data contiguously, how can it be true that &v[n] == &v[0] + n for all 0 <= n < v.size()
.
To phrase this slightly different, is it possible to access all the elements stored in such nested structure "simply" and sequentially (via a pointer or similar) the same way it can be done for a 1-D vector?
No. The elements of a vector
are stored in a dynamically allocated block of memory; otherwise, the capacity of the vector
could not increase. The vector
object just holds a pointer to that block.
The requirement that the elements be stored sequentially applies only to the elements themselves, and not to any dynamically allocated members of those elements.