Get std :: min_element and std :: max_element to return the last value to the iterator?

When using std::min_elementand std::max_element, if more than one element in the range is the lowest / highest, the returned iterator points to the first such element. However, I need it to point to the last such element. Without writing my own function or changing the structure of the input, how can I do this?

My input structure is a C-style array, like int data[N]C ++ 11 or Boost are not available (not my choice ..)

+4
source share
3 answers

You do not need to write your own data structure, you can use std::reverse_iterator:

typedef std::reverse_iterator<int*> Rev;
std::size_t idx = Rev(data) - std::max_element(Rev(data + N), Rev(data)) - 1;

[Live example]

, :

int *p = std::max_element(Rev(data + N), Rev(data)).base() - 1;
+10

, std::minmax_element, :

, . std:: make_pair (, ), . , . , .

+1

:

struct LessWithOrder
{
    bool operator () (const int& lhs, const int& rhs) {
        return lhs != rhs ? lhs < rhs : &lhs < &rhs;
    }
};

struct LessWithInvOrder
{
    bool operator () (const int& lhs, const int& rhs) {
        return lhs != rhs ? lhs < rhs : &lhs > &rhs;
    }
};

it = std::min_element(data, data + N, LessWithInvOrder);
it = std::max_element(data, data + N, LessWithOrder);
0

Source: https://habr.com/ru/post/1569976/


All Articles