Removing item from vector while iterating?

后端 未结 8 1992
小鲜肉
小鲜肉 2020-11-27 15:40

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 mark

相关标签:
8条回答
  • 2020-11-27 16:41

    erase returns a pointer to the next iterator value (same as Vassilis):

    vector <cMyClass>::iterator mit
    for(mit = myVec.begin(); mit != myVec.end(); )
    {   if(condition)
            mit = myVec.erase(mit);
        else
            mit++;
    }
    
    0 讨论(0)
  • 2020-11-27 16:43

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

    (For non-c++0x, you can just replace the lambda below with your own predicate:)

    // 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());
    
    0 讨论(0)
提交回复
热议问题