从向量中删除元素 [英] Deleting elements from a vector

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

问题描述

下面的C ++代码用一些对象填充一个向量,然后删除一些对象,但它看起来像删除了错误的对象:

The following C++ code fills a vector with a number of objects and then removes some of these objects, but it looks like it deletes the wrong ones:

vector<Photon>  photons;

photons = source->emitPhotons();    // fills vector with 300 Photon objects

for (int i=0; i<photons.size();  i++) {
    bool useless = false;

    // process photon, set useless to true for some

    // remove useless photons
    if (useless) {
        photons.erase(photons.begin()+i);
    }
}

我这样做是否正确?我认为 photons.erase(photons.begin()+ i); 可能是问题?

Am I doing this correctly? I'm thinking the line photons.erase(photons.begin()+i); might be the problem?

推荐答案

这是错误的做法,你从来不调整 i 下来,因为你删除..

Definietly the wrong way of doing it, you never adjust i down as you delete..

使用迭代器,这个问题消失了!

Work with iterators, and this problem goes away!

例如

for(auto it = photons.begin(); it != photons.end();)
{
  if (useless)
    it = photons.erase(it);
  else
    ++it;
}

还有其他方法使用算法(如 remove_if erase 等),但上面是最清晰的...

There are other ways using algorithms (such as remove_if and erase etc.), but above is clearest...

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

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