c++ - 使用 std::deque::iterator(在 C++ STL 中)搜索和删除某些元素

标签 c++ stl iterator deque

我在调用以下代码时遇到问题:

#include<deque>
using namespace std;

deque<int> deq = {0,1,2,3,4,5,6,7,8};

for(auto it = deq.begin(); it != deq.end(); it++){
    if(*it%2 == 0)
        deq.erase(it);
}

这导致了段错误。在查看问题后,我发现问题在于 STL 管理双端队列迭代器的方式:如果被删除的元素更接近双端队列的末尾,用于指向被删除元素的迭代器现在将指向 NEXT元素,但不是前一个元素为 vector::iterator做。我知道从 it != deq.end() 修改循环条件至 it < deq.end()可能会解决这个问题,但我只是想知道是否有一种方法可以以“标准形式”遍历和删除双端队列中的某些元素,以便代码也可以与其他容器类型兼容。

最佳答案

http://en.cppreference.com/w/cpp/container/deque/erase

All iterators and references are invalidated [...]

Return value : iterator following the last removed element.

这是在循环内从 STL 容器中删除元素时的常见模式:

for (auto i = c.begin(); i != c.end() ; /*NOTE: no incrementation of the iterator here*/) {
  if (condition)
    i = c.erase(i); // erase returns the next iterator
  else
    ++i; // otherwise increment it by yourself
}

或作为 chris提到你可以使用std::remove_if .

关于c++ - 使用 std::deque::iterator(在 C++ STL 中)搜索和删除某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490219/

相关文章:

c++ - 运算符重载和非成员函数 c++

c++ - 我在这里的绑定(bind)功能做错了什么?

python - 斐波那契数列python

java - 如何为 TreeMap 和 HashMap (Java) 创建一个可迭代的包装器?

c++ - 通过传递参数进行字符串连接

c++ - 如何获取 OCaml 链接器标志以与 C++ cmake 构建链接

c++ - 使用类作为 STL 映射的值 - Undefined Symbol

c++ - 为什么 std::distance 不适用于 const 和非 const 迭代器的混合?

c++ - 我怎么知道 QProcess 什么时候想要读取输入?

c++ - 用指针直接访问STL列表的元素