Home > Back-end >  STL algorithm function with reverse iterators doesn't work
STL algorithm function with reverse iterators doesn't work

Time:11-12

I need to find minimum element in my array, but if amount of minimum elements more than 1, I need to use the most right one.
Consider this code:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    int n;
    cin >> n;
    vector<int> a(n);
    for (int& x : a)
        cin >> x;
    vector<int>::iterator it_min = min_element(a.rbegin(), a.rend());

}

It doesn't work. And it doesn't make sense to me why. Reverse_iterator basically provides all operators needed for correct execution of function. But apparently min_element() expecting only "normal" iterator is being given. Can I somehow bypass that? Ok, I can convert my reverse_iterator to iterator with .base() function member (min_element(a.rbegin().base(), a.rend().base())), but that doesn't resolve my problem since operator is now going forward, not backwards. I could not think of anything sensible. Is there an elegant solution to this problem?

P.S. There's a solution to my problem with custom comparator and it works with normal iterators, but still I want to find out if there is a solution with reverse_iterators:

vector<int>::iterator it_min = min_element(a.begin(), a.end(), [](int min, int b) { return min >= b; });

UPD: After the answer, I understood that everything I said about min_element() is wrong. It can accept reverse_iterators and work with them correctly, but I was confused about why it requires conversion reverse_iterators to iterators, but it didn't required the a.rbegin() and a.rend() to convert to "normal" iterators. It required to convert the returning iterator itself.

CodePudding user response:

You're passing reverse_iterator to min_element, then it returns reverse_iterator too.

Change the code to

vector<int>::reverse_iterator it_min = min_element(a.rbegin(), a.rend());

Or

auto it_min = min_element(a.rbegin(), a.rend());

You can get the vector<int>::iterator from the returned reverse_iterator later by it_min.base() - 1.

  • Related