Search code examples
c++stlreverse-iterator

Reverse Iteration of an STL Algorithm


I have a function that is being called with 2 pointers for arguments, the beginning and and ending of an array. My function will search from the end pointer to the beginning pointer for an element that matches a condition.

If I was trying to iterate forward I could do this with find_if but I need to iterate in reverse. Does the STL have any provision for this?

Note: I can easily do this in a for loop. What I'm looking for is a more elegant solution.


Solution

  • Yes, it is called std::reverse_iterator. An example:

    template<typename RandomAccessIterator>
    void reverse_sort(RandomAccessIterator begin, RandomAccessIterator end) {
        typedef std::reverse_iterator<RandomAccessIterator> r_iter_t;
        std::sort(r_iter_t(end), r_iter_t(begin));
    }
    
    int main() {
        int arr[] = { 1, 2, 3 };
        reverse_sort(std::begin(arr), std::end(arr));
        for(auto i : arr) std::cout << i << "\n";
    }
    

    gives

    3
    2
    1