Is it safe to increase an iterator inside when using it as an argument?
Question
Currently I'm trying to erase a sequence of iterators from a set, however GCC's standard library seems to be broken because std::set::erase(iterator) should return the an iterator (next iterator), however in GCC it returns void (which is standard?)
Anyways I want to write:
myIter = mySet.erase(myIter);
But GCC doesn't like it... So Is it safe to write this instead?
mySet.erase(myIter++);
Edit: And yes I'm checking against mySet.end();
Solution
There is no problem with
mySet.erase(myIter++);
The order of operation is well-defined: myIter is copied into myTempIter, myIter is incremented, and myTempIter is then given to the erase method.
For Greg and Mark: no, there is no way operator++ can perform operations after the call to erase. By definition, erase() is called after operator++ has returned.
OTHER TIPS
First, reread the standard and you'll see that the prototype of the set::erase method is:
void erase(iterator position);
However, the associative containers in the STL are "stable", as erasing an element do not affect the iterators on the other elements. This means that the following line is valid:
iterator to_erase = myIter++;
mySet.erase(to_erase);
// Now myIter is still on the next element