I was coding a little program a while back when I found a Quirk about the stl reverse_iterator
. Use of the iterator is quite easy until you have to delete from one. I tried the normal way of:
vector<sometype>::reverse_iterator myiterator... .. .. myvector.erase(myiterator).
only to find the code didn’t compile. A little baffled I started to looking into why. It turns out you Can’t’ delete from a reverse iterator directly. So the question is How do you delete from a reverse iterator?.
Not wanting to do a full forward traversal to get to the same point I did some Googling. Eventually I found the page: http://www.ddj.com/dept/cpp/184401406
which explains why you can’t delete from the reverse iterator. More importantly it indicates a way that you can delete from the reverse_iterator. So how?
void Manager::raiseWindow(WMWindow* wmwindow)
{
vector<WMWindow*>::reverse_iterator it = windows.rbegin();
while(it != windows.rend())
{
if (*it == wmwindow)
{
// why ++it see http://www.ddj.com/dept/cpp/184401406
windows.erase((++it).base());
windows.push_back(wmwindow);
break;
}
it++;
}
wmwindow->raise();
}
Gives an example of how to do it. However, be aware, doing the above erase, invalidates the iterator so don’t go trying to use it again afterwards! }