function template
<algorithm>

std::minmax_element

default (1)
template <class ForwardIterator>  pair<ForwardIterator,ForwardIterator>    minmax_element (ForwardIterator first, ForwardIterator last);
custom (2)
template <class ForwardIterator, class Compare>  pair<ForwardIterator,ForwardIterator>    minmax_element (ForwardIterator first, ForwardIterator last, Compare comp);
Return smallest and largest elements in range
Returns a pair with an iterator pointing to the element with the smallest value in the range [first,last) as first element, and the largest as second.

The comparisons are performed using either operator< for the first version, or comp for the second.

If more than one equivalent element has the smallest value, the first iterator points to the first of such elements.

If more than one equivalent element has the largest value, the second iterator points to the last of such elements.

Parameters

first, last
Input iterators to the initial and final positions of the sequence to compare. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
comp
Binary function that accepts two elements in the range 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.

Return value

A pair with an iterator pointing to the element with the smallest value in the range [first,last) as first element, and the largest as second.

pair is a class template defined in <utility>.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// minmax_element
#include <iostream>     // std::cout
#include <algorithm>    // std::minmax_element
#include <array>        // std::array

int main () {
  std::array<int,7> foo {3,7,2,9,5,8,6};

  auto result = std::minmax_element (foo.begin(),foo.end());

  // print result:
  std::cout << "min is " << *result.first;
  std::cout << ", at position " << (result.first-foo.begin()) << '\n';
  std::cout << "max is " << *result.second;
  std::cout << ", at position " << (result.second-foo.begin()) << '\n';

  return 0;
}

Output:
min is 2, at position 2
max is 9, at position 3


Complexity

Up to linear in 1.5 times one less than the number of elements compared.

Data races

The objects in the range [first,last) are accessed.

Exceptions

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

See also