athos athos -4 years ago 164
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


and push element at the 2nd level:


But how are vector of vector aligned in memory?

For simple vector, it's a container and align its element continuously, like an
; 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 Source

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


only affects the top row. Your


only affects the i-th column.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download