bremen_matt
bremen_matt

Reputation: 7367

C++ reverse an iterator

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?

Upvotes: 3

Views: 760

Answers (2)

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.

Upvotes: 10

Bathsheba
Bathsheba

Reputation: 234875

No that is not possible in full generality. For example, consider a singly-linked list where you can only iterate in one direction (i.e. it is Forward iterable but not Bidirectional iterable).

A solution in your case would be for the caller of the function to pass reverse iterators.

Reference: https://en.cppreference.com/w/cpp/experimental/ranges#Iterators

Upvotes: 7

Related Questions