使用std :: deque :: iterator(在C ++ STL中)搜索和删除某些元素 [英] Using std::deque::iterator (in C++ STL) for searching and deleting certain elements

查看:211
本文介绍了使用std :: deque :: iterator(在C ++ STL中)搜索和删除某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have encountered a problem invoking the following code:

#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管理deques的迭代器的方式:如果被擦除的元素更接近deque的末尾,用于指向擦除元素的迭代器现在将指向NEXT元素,但不是前面的元素 vector :: iterator 。我理解将循环条件从 it!= deq.end()修改为它< deq.end()可能解决问题,但我只是想知道是否有办法遍历&擦除标准格式中的双端队列中的某些元素,以便代码也可以与其他容器类型兼容。

which resulted in a segmentation fault. After looking into the problem I found that the problem resides in the way the STL manages iterators for deques: if the element being erased is closer to the end of the deque, the iterator used to point to the erased element will now point to the NEXT element, but not the previous element as vector::iterator does. I understand that modifying the loop condition from it != deq.end() to it < deq.end() could possibly solve the problem, but I just wonder if there is a way to traverse & erase certain element in a deque in the "standard form" so that the code can be compatible to other container types as well.

推荐答案

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


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

All iterators and references are invalidated [...]

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

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

This is a common pattern when removing elements from an STL container inside a loop:

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

Or as chris mentioned you could just use std::remove_if.

这篇关于使用std :: deque :: iterator(在C ++ STL中)搜索和删除某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆