C++ reverse an iterator

  • A+
Category:Languages

Is it possible to reverse an iterator in C++?

For instance, a lot of algorithms are designed on the principle that you pass the beginning and ending iterators:

template <typename T> void func( Iterator begin, Iterator end ){     ... } 

Now suppose that internally, I need to iterate forward and backward over the container:

template <typename T> void func( Iterator begin, Iterator end ){     // Iterate forward      ...     // Iterate backward     ... } 

I COULD certainly pass a negative value to std::advance. But I am wondering if it would instead be possible to just convert the iterators to reverse iterators. Is that possible?

 


You can just call std::make_reverse_iterator on the arguments to get a reverse view of the range. The cpp reference page has a demo. That is of course assuming reversal is possible.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: