在迭代时从向量中删除项? [英] Removing item from vector while iterating?

查看:105
本文介绍了在迭代时从向量中删除项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量,其中包含有效或无效的项目。我想要这个向量的大小保持小性能问题,所以我想要被标记为无效的项目从向量中删除。我试着在迭代时这样做,但我得到错误向量迭代器不兼容。

I have a vector that holds items that are either active or inactive. I want the size of this vector to stay small for performance issues, so I want items that have been marked inactive to be erased from the vector. I tried doing this while iterating but I am getting the error "vector iterators incompatible".

vector<Orb>::iterator i = orbsList.begin();

    while(i != orbsList.end()) {
        bool isActive = (*i).active;

        if(!isActive) {
            orbsList.erase(i++);
        }
        else {
            // do something with *i
            ++i;
        }
    }


推荐答案

最可读的方式我在过去是使用 std :: erase 结合 std :: remove_if 。在下面的示例中,我使用此组合从向量中删除任何小于10的数字。

The most readable way I've done this in the past is to use std::erase combined with std::remove_if. In the example below, I use this combination to remove any number less than 10 from a vector.

对于非c ++ 0x,请用您自己的谓词替换下面的lambda:

// a list of ints
int myInts[] = {1, 7, 8, 4, 5, 10, 15, 22, 50. 29};
std::vector v(myInts, myInts + sizeof(myInts) / sizeof(int));

// get rid of anything < 10
v.erase(std::remove_if(v.begin(), v.end(), 
                       [](int i) { return i < 10; }), v.end());

这篇关于在迭代时从向量中删除项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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