调整大小以减少计数时,在 vector::resize() 中重新分配空间? [英] Space reallocated in vector::resize() when resized to lower count?
问题描述
根据Stroustrup:C++ 编程语言 :-
当一个 vector 被调整大小以容纳更多(或更少)元素时,它的所有元素都可能是搬到了新的地点."
"When a vector is resized to accommodate more (or fewer) elements, all of its elements may be moved to new locations."
这是否成立,即使向量被重新调整为更小的尺寸?
Is this holds true, even if the vector is re-sized to smaller size ?
推荐答案
情况 1: 如果请求的新大小大于当前 std::vector::capacity()
那么所有元素都将被重新定位.
情况 2: 如果请求的新大小小于当前的 std::vector::capacity()
,则不会重新定位元素.
Case 1: If the new size being requested is greater than the current std::vector::capacity()
then all elements will be relocated.
Case 2: If the new size being requested is lesser than the current std::vector::capacity()
then there will be no relocation of elements.
标准证据:
标准将vector::resize()
的效果定义为:
C++11 标准 23.3.6.3/12 向量容量:
void resize(size_type sz, const T& c);
效果:
if (sz > size())
insert(end(), sz-size(), c);
else if (sz < size())
erase(begin()+sz, end());
else
; // do nothing
正如 @DavidRodríguez-dribeas 正确指出的那样,std:: 的迭代器失效规则:vector::insert()
操作是:
As @DavidRodríguez-dribeas correctly points out, Iterator invalidation rules for std::vector::insert()
operation are:
23.3.6.5 矢量修饰符
1 [insert,push_back,emplace,emplace_back]
1 [insert,push_back,emplace,emplace_back]
备注:如果新容量大于旧容量,则导致重新分配.如果没有发生重新分配,插入点之前的所有迭代器和引用仍然有效.
Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid.
本质上这意味着:插入点之前的所有迭代器和引用都不会受到影响,除非新容器的大小大于以前的容量,因为在这种情况下,所有元素都可能移动到新位置,从而使指向原始位置的指针/迭代器无效.自 resize()
仅擦除/插入容器末尾的元素[注 1].控制因素归结为根据当前容量请求的大小.
Essentially this means:
All iterators and references before the point of insertion will be unaffected, unless the new container size is greater than the previous capacity because in such a scenario all elements might be moved to new locations thus invalidating pointers/iterators to original location.Since resize()
only erases/inserts elements at the end of the container[Note 1].The governing factor boils down to size being requested as against current capacity.
因此情况 1 结果.
在情况2中std::vector::erase()
会被调用,此时的失效规则是:
In Case 2 std::vector::erase()
will be called and the invalidation rule in this case is:
23.3.6.5 矢量修饰符
迭代器擦除(const_iterator position);
iterator erase(const_iterator position);
3 效果:在擦除点或之后使迭代器和引用无效.
3 Effects: Invalidates iterators and references at or after the point of the erase.
由于[注1],元素只会在最后被移除,不需要所有元素都重新定位.
Since [Note 1], elements will be only removed at end and there is no need of relocation of all elements.
这篇关于调整大小以减少计数时,在 vector::resize() 中重新分配空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!