Why is std::vector contiguous?

后端 未结 5 2117
遥遥无期
遥遥无期 2021-01-03 20:47

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 t

5条回答
  •  失恋的感觉
    2021-01-03 21:18

    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.

提交回复
热议问题