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..)
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With