1

Can I reverse traversal using iterator like below (is it correct?):

for (auto it=foo.end()-1; it != foo.begin()-1; it--)
    DoSomethingHere(it);

I have been doing this OK on vectors. However, from Dr. Dobbs article, it seems that the iterator implementation may vary. I am afraid that it could fail on iterators of other classes.

If the above implementation is correct, is it preferred or is the following reverse-iterator is preferred:

for (auto it = foo.rbegin(); it != foo.rend(); it++)
        DoSomethingHere(it);

Related articles/Q&A for this question of preference can be found in:

  1. How do you erase AND CONTINUE using a std::reverse_iterator?
  2. Dr. Dobbs article
  3. "What are the shortcomings of std::reverse_iterator?"
Community
  • 1
  • 1
Robin Hsu
  • 4,164
  • 3
  • 20
  • 37

1 Answers1

1

foo.begin()-1 produces undefined behavior, so no, it's not a good idea.

Given that you're doing exactly what a reverse iterator is designed to accomplish, it seems like the obvious way to do things. There are certainly limitations on reverse iterators, but for many situations (including what you've outlined above) they're simply irrelevant.

As an aside, your second loop is basically equivalent to:

std::for_each(foo.rbegin(), r.rend(), DoSomethinghere);

Other than the (usually irrelevant) detail that for_each will pass the item the iterator points at, rather than the iterator itself.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111