Finding the position of the smallest value in a std::list

The list of unsorted elements contains a key. There are three possible outcomes to consider:
1. The search will successfully end if the middle element matches the key.
2. If the middle element is greater than the key, the search will continue in the left partition.


Solution 1:

Instead of providing regular iterators, pass reverse iterators for

min_element

.

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

Transform

it

into a conventional iterator again only if required.

Remember to rectify your comparator to

<

instead of

<=

.


Solution 2:


Possible misuse of

std::minmax_element

should be considered, as it provides the most recent maximum element, unlike

std::max_element

.

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

Although not certain, my preference would be to utilize a reverse iterator in conjunction with

std::min_element

.

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


Solution 3:


If you’ve saved your information in a

vector

, implementing a reverse iterator, as previously recommended, would be adequate.

In a broader sense, as noted in reference 1, the Standard Library lacks a

min_element_last

function. Consequently, to address this gap, a viable approach to implementing

min_element_last

could involve the following steps:

template 
using ValueType = typename std::iterator_traits::value_type;
template 
// I models ForwardIterator
// R models StrictWeakOrdering on ValueType
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 
// I models ForwardIterator
// ValueType models TotallyOrdered
I min_element_last(I first, I last) {
    using T = ValueType;
    return min_element_last(first, last, std::less());
}

With the use of

min_element_last

, there is an advantage of being able to utilize it with ForwardIterators that solely adhere to the ForwardIterator concept.

Frequently Asked Questions

Posted in Uncategorized