Why is std::vector contiguous?(为什么 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.
这篇关于为什么 std::vector 是连续的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 std::vector 是连续的?


基础教程推荐
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- 对 STL 容器的安全并行只读访问 2022-10-25
- C++多态 1970-01-01
- C语言3个整数的数组 1970-01-01
- 总计将在节日礼物上花多少钱 1970-01-01
- 用指数格式表示浮点数 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- C语言数组 1970-01-01