我在调用以下代码时遇到问题:
#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/