function template
<algorithm>

std::minmax

default (1)
template <class T>  pair <const T&,const T&> minmax (const T& a, const T& b);
custom (2)
template <class T, class Compare>  pair <const T&,const T&> minmax (const T& a, const T& b, Compare comp);
initializer list (3)
template <class T>  pair<T,T> minmax (initializer_list<T> il);template <class T, class Compare>  pair<T,T> minmax (initializer_list<T> il, Compare comp);
default (1)
template <class T>  constexpr pair <const T&,const T&> minmax (const T& a, const T& b);
custom (2)
template <class T, class Compare>  constexpr pair <const T&,const T&> minmax (const T& a, const T& b, Compare comp);
initializer list (3)
template <class T>  constexpr pair<T,T> minmax (initializer_list<T> il);template <class T, class Compare>  constexpr pair<T,T> minmax (initializer_list<T> il, Compare comp);
Return smallest and largest elements
Returns a pair with the smallest of a and b as first element, and the largest as second. If both are equivalent, the function returns make_pair(a,b).

The versions for initializer lists (3) return a pair with the smallest of all the elements in the list as first element (the first of them, if there are more than one), and the largest as second (the last of them, if there are more than one).

The function uses operator< (or comp, if provided) to compare the values.

The behavior of this function template (version (1)) is equivalent to:
1
2
3
template <class T> pair <const T&,const T&> minmax (const T& a, const T& b) {
  return (b<a) ? std::make_pair(b,a) : std::make_pair(a,b);
}

Parameters

a, b
Values to compare.
comp
Binary function that accepts two values of type T as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered less than the second.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
il
An initializer_list object.
These objects are automatically constructed from initializer list declarators.

T shall support being compared with operator<.
For (3), T shall be copy constructible.

Return value

The lesser of the values passed as arguments.

Example

1
2
3
4
5
6
7
8
9
10
11
// minmax example
#include <iostream>     // std::cout
#include <algorithm>    // std::minmax

int main () {
  auto result = std::minmax({1,2,3,4,5});

  std::cout << "minmax({1,2,3,4,5}): ";
  std::cout << result.first << ' ' << result.second << '\n';
  return 0;
}

Output:
minmax({1,2,3,4,5}): 1 5


Complexity

Up to linear in one and half times the number of elements compared (constant for (1) and (2)).

Exceptions

Throws if any comparison throws.
Note that invalid arguments cause undefined behavior.

See also