CKTIS / C++
std::minmax_element — positions of the minimum and maximum
std::minmax_element finds a range's minimum and maximum and returns a pair of iterators. Ties select the first minimum and last maximum; an empty range requires checking the result before dereferencing.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
std::minmax_element(first, last)
std::minmax_element(first, last, comp)
// Result: std::pair<ForwardIterator, ForwardIterator>std::minmax_element, declared in <algorithm>, searches [first, last) and returns a std::pair of iterators, not copies of values. Its first member points to the minimum and second to the maximum. It requires at least multipass forward iterators; single-pass input iterators are insufficient.
For elements equivalent under the ordering, the algorithm selects the first minimum and last maximum. This importantly differs from std::max_element, which selects the first maximum. An empty range produces {first, first}, meaning {last, last}; do not dereference these iterators. For one element, both iterators point to that element.
In C++23, the classic overload without comp uses operator<. For pointers, this operator does not guarantee the strict total order provided by std::less. The overload with comp requires a strict weak ordering: comp(a, b) means that a precedes b; do not use <=. The algorithm does not sort the range. Returned iterators may be used only while they remain valid.
For N elements, it performs at most max(floor(3 * (N - 1) / 2), 0) comparisons, giving linear complexity. Overloads taking an execution policy as their first argument also exist; the example uses the ordinary overload without a policy.
Examples
#include <algorithm>
#include <array>
#include <iostream>
int main() {
const std::array<int, 5> values{4, 1, 9, 1, 9};
const auto [lo, hi] = std::minmax_element(values.begin(), values.end());
if (lo != values.end()) {
std::cout << "min=" << *lo << " index=" << (lo - values.begin()) << '\n';
std::cout << "max=" << *hi << " index=" << (hi - values.begin()) << '\n';
}
}
Result
min=1 index=1 max=9 index=4
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.