std::minmax

Header: <algorithm>

Returns the lowest and the greatest of the given values.

# Declarations

template< class T >
std::pair<const T&, const T&> minmax( const T& a, const T& b );

(since C++11) (constexpr since C++14)

template< class T, class Compare >
std::pair<const T&, const T&> minmax( const T& a, const T& b,
Compare comp );

(since C++11) (constexpr since C++14)

template< class T >
std::pair<T, T> minmax( std::initializer_list<T> ilist );

(since C++11) (constexpr since C++14)

template< class T, class Compare >
std::pair<T, T> minmax( std::initializer_list<T> ilist,
Compare comp );

(since C++11) (constexpr since C++14)

# Parameters

# Notes

For overloads (1,2), if one of the parameters is a temporary, the reference returned becomes a dangling reference at the end of the full expression that contains the call to minmax:

# Example

#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6};
    std::srand(std::time(0));
    std::pair<int, int> bounds = std::minmax(std::rand() % v.size(),
                                             std::rand() % v.size());
 
    std::cout << "v[" << bounds.first << "," << bounds.second << "]: ";
    for (int i = bounds.first; i < bounds.second; ++i)
        std::cout << v[i] << ' ';
    std::cout << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2239C++11T was required to be LessThanComparable for overloads (2,4)not required

# See also