函式模板
<algorithm>

std::max_element

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

比較是使用第一個版本的 operator<,或者第二個版本的 comp;如果不存在其他元素小於該元素,則該元素為最大。如果多個元素滿足此條件,則返回的迭代器指向滿足條件的首個元素。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
template <class ForwardIterator>
  ForwardIterator max_element ( ForwardIterator first, ForwardIterator last )
{
  if (first==last) return last;
  ForwardIterator largest = first;

  while (++first!=last)
    if (*largest<*first)    // or: if (comp(*largest,*first)) for version (2)
      largest=first;
  return largest;
}

引數

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

返回值

指向範圍中最大值的迭代器,如果範圍為空則返回 last

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// min_element/max_element example
#include <iostream>     // std::cout
#include <algorithm>    // std::min_element, std::max_element

bool myfn(int i, int j) { return i<j; }

struct myclass {
  bool operator() (int i,int j) { return i<j; }
} myobj;

int main () {
  int myints[] = {3,7,2,5,6,4,9};

  // using default comparison:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7) << '\n';

  // using function myfn as comp:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myfn) << '\n';

  // using object myobj as comp:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myobj) << '\n';

  return 0;
}

輸出
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9


複雜度

線性時間,等於元素數量減一的比較次數。

資料競爭

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

異常

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

另見