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

Wil*_*ang 4 c++ iterator stl 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);
}
Run Code Online (Sandbox Code Playgroud)

这导致了分段错误.在查看问题后,我发现问题在于STL管理deques的迭代器的方式:如果被擦除的元素更接近deque的末尾,用于指向擦除元素的迭代器现在将指向NEXT元素,但不是前一个元素vector::iterator.据我所知,从修改的循环条件it != deq.end(),以it < deq.end()可能可能解决这个问题,但我不知道是否有遍历&在"标准形式"一个双端队列擦除某些元件,使得代码可以是其他容器类型兼容的方式同样.

sya*_*yam 18

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

所有迭代器和引用都无效[...]

返回值:最后一个删除元素后的迭代器.

从循环内的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
}
Run Code Online (Sandbox Code Playgroud)

或者克里斯提到你可以使用std::remove_if.


Fra*_*ser 11

要使用擦除删除习惯用法,您可以执行以下操作:

deq.erase(std::remove_if(deq.begin(),
                         deq.end(),
                         [](int i) { return i%2 == 0; }),
          deq.end());
Run Code Online (Sandbox Code Playgroud)

请务必#include <algorithm>使std::remove_if用.