pop_back()是否真的会使std :: vector上的所有迭代器无效? [英] Does pop_back() really invalidate *all* iterators on an std::vector?
问题描述
std::vector<int> ints;
// ... fill ints with random values
for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )
{
if(*it < 10)
{
*it = ints.back();
ints.pop_back();
continue;
}
it++;
}
此代码不起作用,因为调用 pop_back()
时, it
无效.但是我在 std :: vector :: pop_back()
中找不到任何有关迭代器无效的文档.
This code is not working because when pop_back()
is called, it
is invalidated. But I don't find any doc talking about invalidation of iterators in std::vector::pop_back()
.
您是否有与此相关的链接?
Do you have some links about that?
推荐答案
对 pop_back()
删除向量中的最后一个元素,因此对该元素的迭代器无效. pop_back()
调用不会使最后一个元素之前的项目的迭代器无效,只有重新分配才能做到.摘自Josuttis的"C ++标准库参考":
The call to pop_back()
removes the last element in the vector and so the iterator to that element is invalidated. The pop_back()
call does not invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' "C++ Standard Library Reference":
插入或删除元素使引用,指针无效,并且引用以下内容的迭代器元素.如果插入导致重新分配,它会使所有引用,迭代器和指针.
Inserting or removing elements invalidates references, pointers, and iterators that refer to the following element. If an insertion causes reallocation, it invalidates all references, iterators, and pointers.
这篇关于pop_back()是否真的会使std :: vector上的所有迭代器无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!