Deleting contents frmo std::vector

I have a scenario where I need to delete the contents of an std::vector.


1
2
3
4
5
6
7
8
    // some code that populates std::vector.

    for( // Traverse through some list of objects )
    {
        1. for each object in the for-loop, get a value associated with it.
        2. Here, I need to delete the entries in the vector which match
           the value returned above.
    }


How do I ensure this?.

Note that I might most likely need to delete data from the vector in different iterations of the enclosing for-loop. I came across erase-remove idiom but it seems it invalidates the iterator & I am not sure how bad it can go with different corner usecases.

Please suggest.

Thansk,
Pavan.
Last edited on
I think I got it.

1
2
3
4
5
6
7
8
9
10
11
    for( ; iter!=myVec.end() ; )
    {
        if( *iter == var_1 || *iter == var_2 )
        {
            myVec.erase( std::remove( myVec.begin(), myVec.end(),*iter ), myVec.end() );
        }
        else
        {
            ++iter;
        }
    }
Last edited on
Please use code tags when posting code.
http://www.cplusplus.com/articles/jEywvCM9/

As for the problem, I was going to say that you should go forward with the erase-remove idiom which you already learned about.

http://en.wikipedia.org/wiki/Erase-remove_idiom
Topic archived. No new replies allowed.