Stl::reverse iterator

Posted by Benjamin Close on November 13, 2008 under Programming | Be the First to Comment

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::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)
 {
   <strong>vector&lt;WMWindow*&gt;::reverse_iterator it = windows.rbegin();</strong>
   while(it != windows.rend())
   {
     if (*it == wmwindow)
     {
      // why ++it see <a class="external free" title="http://www.ddj.com/dept/cpp/184401406" rel="nofollow" href="http://www.ddj.com/dept/cpp/184401406">http://www.ddj.com/dept/cpp/184401406</a>
      <strong>windows.erase((++it).base());</strong>
      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! }



Donations keep this site alive

Add A Comment

*