Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::vector contiguous?

Tags:

Besides the fact that the standard defines it to be contiguous, why is std::vector contiguous?

If it runs out of space, it needs to reallocate a new block and copy the old block to the new one before continuing.

What if it wasn't contiguous? When the storage fills up, it would just allocate a new block and keep the old block. When accessing through an iterator, it would do simple >, < checks to see which block the index is in and return it. This way it doesnt need to copy the array every time it runs out of space.

Would this really work/be better? or am i missing something?

like image 914
deller Avatar asked Nov 09 '13 12:11

deller


People also ask

Is std::vector continuous?

Yes, the elements of a std::vector are guaranteed to be contiguous.

Is std :: array contiguous?

Yes the memory of std::array is contiguous.

Is std :: list contiguous?

All the data in a vector is contiguous where the std::list allocates separately memory for each element.

Are vectors stored contiguous?

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays.


Video Answer


1 Answers

If std::vector didn't guarantee contiguousness, a new container would be invented which did.

The contiguity guarantee makes it easier to inter-operate with existing code that expects a contiguous array, and also gives very good performance because it is cache-friendly. (Inserting/deleting in the middle is in practice very fast for moderate sizes because of this.)

Copying the array on expansion is surprisingly cheap - if you append to a vector a million elements one at a time, each element will have been copied on average around once.

like image 150
Alan Stokes Avatar answered Sep 28 '22 04:09

Alan Stokes