my question was:
for( it = l.begin(); it != l.end(); ++it )
{
if(...) l.erase(it--);
}
Is that OK? [...]
Victor wrote:
No. If the first element is to be erased, you
will make 'it' invalid
by decrementing it past the 'l.begin()'.
Incrementing it again does
not necessarily bring it back to be valid -
undefined behaviour.
Are you sure, that this behaviour is undefined
by ANSI c++ ?
I use GNU compilers, where STL is implemented
by SGI. Here, as a matter of fact, list is
implemented as the circular structure, i.e.:
list<T> mylist;
list<T>::iterator p=mylist.end();
p++; assert(p==mylist.end());
p--; assert(p==mylist.end());
//now insert exactly one element:
mylist.push_front(something_of_type_T);
p=mylist.begin();
p--; assert(p==mylist.end());
p++; assert(p==mylist.begin());
is a valid code - none of the asserts fail.
In another words, one can traverse the same
list infinitely many times by repetitive
++ only (or -- only). During this, the
interator will be invalid only one time
each cycle - when passing its end() value.
I always thought, that such a behaviour
of list::iterator is implementation-independend.
Has anybody seen a counterexample, i.e. an
implementation which is still ANSI c++ compliant,
by does not obey "circularity" ?
Best regards from Poland :-)
O.C.