tags:

views:

379

answers:

2

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++);

Thanks!

Edit: And yes I'm checking against mySet.end();

+9  A: 

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.

Camille
What you say is true only because the operator++ has been redefined by the classes. For PODs, the operator is actually called after the line!
PierreBdR
Yes, it is an interesting remark. And the whole point is that the order of operations is irrelevant for POD types, since incrementation is always well-defined. Well you can always imagine strange cases where the method has some access to a reference to the POD-variable, but that is not recommended.
Camille
+3  A: 

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
PierreBdR
Special thanks for remembering about the fact that sets don't have random access iterators!
Robert Gould