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 是连续的?
- 运算符优先级 1970-01-01
- “纯虚函数调用"在哪里?崩溃从何而来? 2022-10-18
- C++指向数组的指针 1970-01-01
- 使用最流行的转义序列 1970-01-01
- 打印扩展的ASCII字符 1970-01-01
- 使用整数值初始化char类型的变量 1970-01-01
- 使用来自float.h和limits的数据,找到该系统的一些 1970-01-01
- C语言可使用的所有转义序列 1970-01-01
- C语言求模 1970-01-01
- C++浮点常数 1970-01-01