我在调用以下代码时遇到问题:
#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管理双队列迭代器的方式上:如果被擦除的元素更接近双队列的末尾,那么用于指向被擦除元素的迭代器现在将指向下一个元素,而不是像vector::iterator那样指向前一个元素。我知道将循环条件从it != deq.end()修改为it < deq.end()可能会解决这个问题,但我只是想知道是否有一种方法可以在“标准形式”中遍历和擦除双队列中的某些元素,以便代码也可以兼容其他容器类型。
发布于 2013-03-19 10:02:57
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
}或者就像chris提到的,你可以直接使用std::remove_if。
发布于 2013-03-19 10:19:47
要使用erase-remove idiom,您需要执行以下操作:
deq.erase(std::remove_if(deq.begin(),
deq.end(),
[](int i) { return i%2 == 0; }),
deq.end());要使std::remove_if可用,请务必使用#include <algorithm>。
https://stackoverflow.com/questions/15490219
复制相似问题