为什么 std::vector 是连续的?
除了标准定义它是连续的,为什么 std::vector 是连续的?
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?
推荐答案
如果 std::vector
不能保证连续性,就会发明一个新的容器来保证连续性.
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.
相关文章