[英]Can you pop_back a vector and still use the iterator to the last element?
I wonder what happens if I have an iterator on the last element of the vector and do pop_back
. 我想知道如果我在向量的最后一个元素上有一个迭代器并且执行pop_back
会发生什么。
std::set<int> s;
s.insert(5);
std::vector<int> v = {1, 2, 3, 4, 5};
for (auto it = v.begin(); it != v.end();) {
if (s.count(*it)) {
std::swap(*it, v.back());
v.pop_back();
} else {
++it;
}
}
Code above works properly ( v
is {1, 2, 3, 4}
after that block) at least with clang, but is it correct to check if it == v.end()
if it
is invalidated? 上面的代码正常工作( v
在该块之后是{1, 2, 3, 4}
)至少使用clang,但是如果it
是无效的,检查它是否正确it == v.end()
是否正确?
Your instincts are good; 你的直觉很好; vector::pop_back
invalidates iterators and references to the last element . vector::pop_back
使迭代器和对最后一个元素的引用无效 。 If it
is such an iterator, then it will be invalidated, and thus cannot be compared with v.end()
. 如果it
是这样的迭代器,那么它将被无效,因此无法与v.end()
进行比较。
It would be much better to fix this by using algorithms and the erase-remove idiom: 通过使用算法和擦除删除习惯来解决这个问题要好得多:
auto last_it = std::remove_if(v.begin(), v.end(), [&](const auto &val) {return s.count(val) != 0;});
v.erase(last_it, v.end());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.