athos athos - 29 days ago 8
C++ Question

How is a Vector of Vector aligned in memory?

I understand as Set size of vector of vectors at run time
describes, one can declare vector of vector as

vector<vector<int> > ref;


then resize the first level by

ref.resize(i);


and push element at the 2nd level:

ref[i].push_back(23);


But how are vector of vector aligned in memory?

For simple vector, it's a container and align its element continuously, like an
array
; but in the case of vector of vector, I couldn't see the picture.

As the size of each inner vector (the vector in vector of vector) size might change, does the outer vector of vector (the vector in vector of vector) align inner vectors continously? Does the outer vector researve memeory space for each inner vector? what if one vector overshoot?

Answer

The size of the vector<int> struct that is stored in ref is constant. Common implementations has this at around 12 bytes.

So ref manages roughly ref.capacity() * 12 bytes of continuous storage.

Each element/vector<int> in ref manages its own integers independent of the elements ref manages. In the artistic rendering below ref.size() == ref.capacity() for the sake of simplicity.

Pretty picture

So your

ref.resize(i);

only affects the top row. Your

ref[i].push_back(23);

only affects the i-th column.