Search code examples
c++standard-library

c++ erase the std::vector.end() while looping over all iterators


I want to erase some iterator from a vector, so this is what I have now.

void function(std::vector <class*> & vector)
{
    std::vector <class*>::iterator it;
    for(it = vector.begin(); iter != vector.end(); ++iter)
        {
            if(it->value == 1)
                vector.erase(it);
        }
    Display(vector);
    return;
}

Apparently this code gives me an error when the iterator got removed is the last one in the vector, otherwise seems it's working fine. I know it might not be desirable behavior to modify vector inside such a loop, but if I have to do this, what will be the best way?

Thanks.


Solution

  • for (it = vector.begin(); it != vector.end(); )
    {
        if (it->value == 1)
            it = vector.erase(it);
        else
            ++it;
    }
    

    But for this case, you should actually just use std::remove_if with an appropriate predicate.