Deleting elements from a vector

后端 未结 5 1113
独厮守ぢ
独厮守ぢ 2021-01-23 17:48

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

        
5条回答
  •  借酒劲吻你
    2021-01-23 18:15

    You should work with stl::list in this case. Quoting the STL docs:

    Lists have the important property that insertion and splicing do not invalidate iterators to list elements, and that even removal invalidates only the iterators that point to the elements that are removed.

    So this would go along the lines of:

    std::list photons;
    photons = source->emitPhotons();
    std::list::iterator i;
    for(i=photons.begin();i!=photons.end();++i)
    {
        bool useless=false;
        if(useless)
            photons.erase(i);
    }
    

提交回复
热议问题