函式模板
<algorithm>

std::minmax_element

預設 (1)
template <class ForwardIterator>  pair<ForwardIterator,ForwardIterator>    minmax_element (ForwardIterator first, ForwardIterator last);
自定義 (2)
template <class ForwardIterator, class Compare>  pair<ForwardIterator,ForwardIterator>    minmax_element (ForwardIterator first, ForwardIterator last, Compare comp);
返回範圍中的最小和最大元素
返回一個pair,其第一個元素是指向範圍 [first,last) 中值最小的元素的迭代器,第二個元素是指向值最大的元素的迭代器。

第一個版本使用 operator< 進行比較,第二個版本使用 comp 進行比較。

如果存在多個等價的最小元素,第一個迭代器指向其中第一個元素。

如果存在多個等價的最大元素,第二個迭代器指向其中最後一個元素。

引數

first, last
輸入迭代器,指向要比較的序列的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
comp
二元函式,接受範圍中的兩個元素作為引數,並返回一個可轉換為 bool 的值。返回的值指示第一個引數傳遞的元素是否被視為小於第二個引數。
該函式不得修改其任何引數。
這可以是指向函式的指標,也可以是函式物件。

返回值

一個pair,其第一個元素是指向範圍 [first,last) 中值最小的元素的迭代器,第二個元素是指向值最大的元素的迭代器。

pair 是一個在 <utility> 中定義的類模板。

示例

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;
}

輸出
min is 2, at position 2
max is 9, at position 3


複雜度

最多線性於 1.5 倍比比較的元素數量減一。

資料競爭

訪問範圍 [first,last) 中的物件。

異常

如果任何比較操作丟擲異常,則該函式丟擲異常。
請注意,無效引數會導致未定義行為

另見