Erase/Remove contents from the map (or any other STL container) while iterating it

前端 未结 9 1376
无人及你
无人及你 2020-12-01 07:55

Allegedly you cannot just erase/remove an element in a container while iterating as iterator becomes invalid. What are the (safe) ways to remove the elements that meet a cer

9条回答
  •  半阙折子戏
    2020-12-01 08:43

    Viktor's solution has the upside of being able to do something with the element before removing. (I wasn't able to do this with remove_if or remove_copy_if.) But I prefer to use std::find_if so I never have to increment the iterator myself:

    typedef vector int_vector;
    int_vector v;
    
    int_vector::iterator itr = v.begin();
    for(;;)
    {
        itr = std::find_if(itr, v.end(), Predicate(4));
        if (itr == v.end())
        {
            break;
        }
    
        // do stuff with *itr here
    
        itr = v.erase(itr);  // grab a new, valid iterator
    }
    

    Where Predicate could be bind1st( equal_to(), 4 ) or something like this:

    struct Predicate : public unary_function
    {
        int mExpected;
        Predicate(int desired) : mExpected(desired) {}
        bool operator() (int input)
        {
            return ( input == mExpected );
        }
    };
    

提交回复
热议问题