简体   繁体   中英

c++ STL min_element

I want to find the minimum element in an array, but if the minimum element appears more than once, then I want the last occurrence of the element. I used std::min_element() with my comp() function.

vector<int>::iterator it=min_element(input.begin(), input.end(),comp);
cout << *it << endl;
cout << distance(input.begin(), it);

bool comp(int a, int b) {
if (a <= b)
    return true;
else
    return false;
}

This code is giving an error saying invalid comparator on input 3 3 4.

Give min_element reverse iterators instead:

vector<int>::reverse_iterator it=min_element(input.rbegin(), input.rend(),comp);

Then convert it back to a "normal" iterator iff you need to.

And don't forget to correct your comparator; it needs to be < not <= .

You might abuse of std::minmax_element which returns the last biggest element contrary to std::max_element :

auto last_min_it = std::minmax_element(input.begin(), input.end(), std::greater<>{}).second;

I would probably use reverse iterator with std::min_element , though:

auto min_rev_it = std::min_element(input.rbegin(), input.rend());

If your data are stored in a vector , then the use of a reverse iterator should suffice, as already suggested.

More generally, the Standard Library does not provide a min_element_last function, as also commented in 1 . In this respect, a possible implementation of min_element_last may read:

template <typename I>
using ValueType = typename std::iterator_traits<I>::value_type;

template <typename I, typename R>
// I models ForwardIterator
// R models StrictWeakOrdering on ValueType<I>
I min_element_last(I first, I last, R cmp) {
    if (first == last) return last;
    I curr = first;
    ++first;
    while (first != last) {
        if (!cmp(*curr, *first)) {
            curr = first;
        }
        ++first;
    }
    return curr;
}

template <typename I>
// I models ForwardIterator
// ValueType<I> models TotallyOrdered
I min_element_last(I first, I last) {
    using T = ValueType<I>;
    return min_element_last(first, last, std::less<T>());
}

The advantage would be the possibility of using min_element_last also with iterators that only model the ForwardIterator concept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM