Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

When using std::min_element and 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 have need for it to point to the last such element. Without writing my own function or reversing the input data structure, how can I do this?

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

like image 581
Neil Kirk Avatar asked Dec 20 '22 08:12

Neil Kirk


2 Answers

You don't have 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]

Or, if you want the pointer:

int *p = std::max_element(Rev(data + N), Rev(data)).base() - 1;
like image 108
Angew is no longer proud of SO Avatar answered Dec 21 '22 22:12

Angew is no longer proud of SO


Considering only the last greatest element there's already std::minmax_element , which returns:

a pair consisting of an iterator to the smallest element as the first element and an iterator to the greatest element as the second. Returns std::make_pair(first, first) if the range is empty. If several elements are equivalent to the smallest element, the iterator to the first such element is returned. If several elements are equivalent to the largest element, the iterator to the last such element is returned.

like image 20
w.b Avatar answered Dec 21 '22 20:12

w.b