Search code examples
c++iteratorreverse-iterator

How can you use a reverse iterator with an iterator that is a proxy


Given you have an iterator that is effectively a proxy and contains the data that it returns, how can you make a reverse iterator?

std::reverse_iterator implementation of the dereferencing operator creates a temporary object which it then decrements and dereferences, with code that is something like:

  reference operator*() const {
    iterator tmp = current;
    return *--tmp;
  }

with the result that what it returns to you is a pointer to data that goes out of scope before you get hold of it.

This has rather unfortunate results.

How can you get round this?


Solution

  • It looks like you'll need to write your own custom reverse iterator implementation for this specific case since your iterator type is not compatible with this specific implementation of reverse_iterator.

    According to http://en.cppreference.com/w/cpp/iterator/reverse_iterator, some implementations do also store a decremented copy of the iterator but not all. Boost::reverse_iterator does not appear to store an additional copy.