tags:

views:

235

answers:

2

I recently learned about the right way to work with reverse iterators in C++ (specifically when you need to erase one). (See this question and this one.)

This is how you're supposed to do it:

typedef std::vector<int> IV;
for (IV::reverse_iterator rit = iv.rbegin(), rend = iv.rend();
     rit != rend; ++rit)
{
  // Use 'rit' if a reverse_iterator is good enough, e.g.,
  *rit += 10;
  // Use (rit + 1).base() if you need a regular iterator e.g.,
  iv.erase((rit + 1).base());
}

But I think this is much better:

for (IV::iterator it = iv.end(), begin = iv.begin();
     it-- != begin; )
{
  // Use 'it' for anything you want
  *it += 10;
  iv.erase(it);
}

Pros:

  • Uses a familiar idiom for reverse for-loops
  • Don't have to remember (or explain) the +1
  • Less typing
  • Works for std::list too: it = il.erase(it);
  • If you erase an element, you don't have to adjust the iterator
  • If you erase, you don't have to recompute the begin iterator

Cons:

  • You tell me. What's wrong with it?
+3  A: 

For what it's worth, Scott Meyers' Effective STL recommends that you just stick with a regular ol' iterator (Item 26).

Wesley Petrowski
It also says to avoid explicit loops, and `reverse_iterator` is sometimes necessary to accomplish that. Item 26 is talking about explicit loops only.
Billy ONeal
+4  A: 

The reason for reverse iterators is that the standard algorithms do not know how to iterate over a collection backwards. For example:

#include <string>
#include <algorithm>
std::wstring foo(L"This is a test, with two letter a's involved.");
std::find(foo.begin(), foo.end(), L'a'); // Returns an iterator pointing
                                        // to the first a character.
std::find(foo.rbegin(), foo.rend(), L'a').base()-1; //Returns an iterator
                                                 // pointing to the last A.
std::find(foo.end(), foo.begin(), L'a'); //WRONG!! (Buffer overrun)

Use whichever iterator results in clearer code.

Billy ONeal
Good point that there may be some generic algos that will work on reverse_iterators and there may not be a 'reverse' version of that algo for use on regular iterators. For wstring you could use find_last_of, but if it were some other type of container that's not an option.
Dan
BTW your second std::find() call returns an iterator pointing to '\'' (the apostrophe). This points to the 'a': std::wstring::iterator iter = (std::find(foo.rbegin(), foo.rend(), 'a') + 1).base();
Dan
Good point, fixed :)
Billy ONeal