I get how vectors works in general as far as memory allocation is concerned, but what happens when you use a vector to store a vector of some simple type.
The simple solution is to always use pointers for the inner vectors, but then what's the difference between declaring something like "vector<vector<int>> a
" to declaring something like "vector<vector<int>*> b
"?
In the case where it's actually a contiguous block of memory for the inner vectors what happens when a reallocation breaks the boundaries of memory that could be used? Is everything copied to a new block? That seems unlikely because it's so expensive, but then it goes back to the question in the second paragraph.
Thanks for your time!
A vector<vector<int>>
uses std::allocator
for both the outer and inner vectors. These are all independent allocations.
std::vector
supports custom allocators, and in particular it supports std::scoped_allocator_adaptor
to share an allocator across nesting levels. So you could write an allocator to try to keep things in contiguous memory. But as you already noted, there are limits to what you can achieve. For every allocator, there's always an allocation pattern that will fragment allocations.