i want to erase some elements in the list pointed by a reversed iterator,and i wrote like this
list<int>::reverse_iterator it=mylist.rbegin();
mylist.erase(it.base());
but after the erasing of a specific element,the iterator it is no longer valid.so i also need to make sure that the iterator will move to the next element automatically,so i changed my code to this:
it=mylist.erase(it.base());
and that's when i encountered the problem.
the compiling error says that a const_iterator type can't be converted to a reverse_iterator type.
The problem is erase returns a const_iterator (note, forward iterator) rather than a non-const reverse_iterator. Since there is no implicit conversion between the two, you get the compile error. I think you can do what you want with
mylist.erase((it++).base());
although there is nothing wrong with explicitly creating a temporary iterator to handle the delete.
Also, take a look at the list<T>::remove and list<T>::remove_if methods, which may simplify your code a bit.
The reason this is bad is because it modifies 'itr' twice in the same sequence point, which has undefined behavior and may cause your program to explode if the compiler decides to make the changes in a certain order.
erase modifies the contents of itr (it erases it) and then the ++ operator increments the iterator, which may not be possible if the iterator was erased.
So if the compiler decides to erase first (which is likely, but not guaranteed), you're hosed.
The moral of the story here is to avoid compound statements, as they can lead to some unexpected and nasty bugs unless you really know what's going on. It doesn't hurt to break this up into 2 separate lines of code.
I believe 'itr++' resolves to list<T>::iterator::operator++(). Erase would not be able to manipulate 'itr', because it needs to know the result of the operator++ method, guaranteeing that 'itr++' takes place before anything is erased. It's possible to implement the 'operator++()' method to return any random iterator object; it won't necessarily be the same as the object on which the method is called.
I do agree that having an explicitly defined temp iterator is clearer, but I don't think your logic above is correct. Of course, I've been wrong before :)
I believe 'itr++' resolves to list<T>::iterator::operator++(). Erase would not be able to manipulate 'itr', because it needs to know the result of the operator++ method