你能pop_back一个向量,并且仍然使用迭代器到最后一个元素吗?
Can you pop_back a vector and still use the iterator to the last element?
我想知道如果我在向量的最后一个元素上有一个迭代器并执行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());
相关文章:
- 对于set上的循环-获取next元素迭代器
- 访问要输出的矢量迭代器元素
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- 如何通过查找迭代器结果分配给一组对的元素
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 将迭代器作为 3 个元素的滑动窗口,可以超调边界(可能使用 Boost)
- C++链表最后一个元素的迭代器?
- 使用索引与迭代器将向量迭代到倒数第二个元素
- 提升堆元素句柄比较和 MSVC 迭代器调试工具
- 如果我有一个指向矢量元素的指针,而不是迭代器,如何删除它?
- 使用迭代器打印矢量元素
- C++ std::vector语言 - 如何修改迭代器指定的元素?
- 你能pop_back一个向量,并且仍然使用迭代器到最后一个元素吗?
- 优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
- C++ 当容器在使用前被破坏/修改时发出警告(通过引用元素或迭代器使用)
- 如何从该列表的元素中获取 std::list<T>::迭代器?
- 如何在c++中记忆迭代器元素