你能pop_back一个向量,并且仍然使用迭代器到最后一个元素吗?

Can you pop_back a vector and still use the iterator to the last element?

本文关键字:迭代器 元素 最后一个 back pop 向量 一个 你能      更新时间:2023-10-16

我想知道如果我在向量的最后一个元素上有一个迭代器并执行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;
}
}

上面的代码至少在 clang 中工作正常(v在该块之后{1, 2, 3, 4}(,但是检查it == v.end()是否it无效是否正确?

你的直觉很好;vector::pop_back使迭代器和对最后一个元素的引用无效。如果it是这样的迭代器,那么它将被失效,因此无法与v.end()进行比较。

通过使用算法和擦除删除习惯法来解决此问题会好得多:

auto last_it = std::remove_if(v.begin(), v.end(), [&](const auto &val) {return s.count(val) != 0;});
v.erase(last_it, v.end());