[cs13001] Question after class

Mikhail Nesterenko mikhail at cs.kent.edu
Mon Mar 10 23:11:50 EDT 2014



> There was a question after class about modifying a container in a
> loop without breaking things with the iterator. I had mentioned my
> solution in Java and you wanted to look up what the standard was for
> C++.


In general, modifying a container invalidates iterators. However,
operations that invalidate iterators often return "convenient"
iterators. For example, erase() returns the iterator to the next
element (in the updated container) after the one erased. Hence the
idiom:

for(vector<int>::iterator it=myVector.begin(); 
    it != myVector.end(); 
    /* no increment here */)
    if(must_erase)
        it = myVector.erase(it);
    else
        ++it;


More information about the cs13001 mailing list