Why is std::vector contiguous?

后端 未结 5 2115
遥遥无期
遥遥无期 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

    As a complement to the other answers (they are quite complete), there is one situation when you do prefer vectors to not be contiguous: when you need to resize a vector concurrently. That is why Intel Thread Building Block provides tbb::concurrent_vector, which is more or less what you said you would expect

    "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."

    Then, a comparison between tbb::concurrent_vector and std::vector would give you a better understanding of the advantages (speed) and disadvantages (cannot grow std::vector concurrently) of contiguous memory. I expect tbb::concurrent_vector to be better optimized than std::deque and that is why tbb::concurrent_vector vs std::vector is a more fair comparison.

提交回复
热议问题