我在调用以下代码时遇到问题:
#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()
to it < deq.end()
可能会解决这个问题,但我只是想知道是否有一种方法可以以“标准形式”遍历和删除双端队列中的某些元素,以便代码也可以与其他容器类型兼容。
http://en.cppreference.com/w/cpp/container/deque/erase 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
}
Or as chris https://stackoverflow.com/users/962089/chris提到你可以使用std::remove_if http://en.cppreference.com/w/cpp/algorithm/remove.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)