复制后的 std::vector 容量
- vector::operator= 会改变向量容量吗?如果是这样,怎么办?
- Vector的复制构造函数是否复制容量?
我查看了文档但找不到具体的答案。它依赖于实现吗?
- Does vector::operator= change vector capacity? If so, how?
- Does vector's copy constructor copy capacity?
I looked through documentation but could not find a specific answer. Is it implementation dependent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您所保证的是:
因此,实现想要添加多少额外或少量取决于实现。我认为大多数人在复印时都会使容量与大小匹配,但不能降低容量。 (由于上面的第 2 点;在有足够空间的情况下重新分配是不允许的。)
* 大多数情况下。请参阅下面查尔斯的评论。
All you're guaranteed is that:
So how much extra or little an implementation wants to put is up to the implementation. I think most will make capacity match size, when copying, but it cannot lower capacity. (Because of number 2 above; reallocating while there's enough room is not allowed.)
* Mostly. See Charles' comments below.
它可能会改变容量。仅当先前的容量太小而无法容纳新的大小时,才会发生这种情况。如果是这样,新容量至少等于新大小,但也可以是更大的值。
根据表 65 C++03 中的容器要求,
X u (a);
和X u = a;
均等同于X u; u = a;
。在默认构建向量之后,这使得复制向量与 op= 情况相同。It might change capacity. This happens only if the previous capacity was too small to hold the new size. If so, the new capacity is at least equal to the new size, but could be a larger value.
Per Table 65 Container requirements in C++03,
X u (a);
andX u = a;
are both equivalent toX u; u = a;
. This makes the copy ctor identical to the op= case, after default constructing the vector.正如我之前所写,副本不需要 - 通常也不需要 - 保留原始向量的容量。
As i wrote before, the copy need not - and usually DOES NOT - retain the capacity of the original vector.
它取决于实现。大多数实践中将向量缩小到最小尺寸。
It is implementation dependent. Most in practice shrink the vectors to the minimum size.