函式模板
<algorithm>

std::max

預設 (1)
template <class T> const T& max (const T& a, const T& b);
自定義 (2)
template <class T, class Compare>  const T& max (const T& a, const T& b, Compare comp);
預設 (1)
template <class T> const T& max (const T& a, const T& b);
自定義 (2)
template <class T, class Compare>  const T& max (const T& a, const T& b, Compare comp);
初始化列表 (3)
template <class T> T max (initializer_list<T> il);template <class T, class Compare>  T max (initializer_list<T> il, Compare comp);
預設 (1)
template <class T> constexpr const T& max (const T& a, const T& b);
自定義 (2)
template <class T, class Compare>  constexpr const T& max (const T& a, const T& b, Compare comp);
初始化列表 (3)
template <class T> constexpr T max (initializer_list<T> il);template <class T, class Compare>  constexpr T max (initializer_list<T> il, Compare comp);
返回最大的
返回 ab 中較大的一個。如果兩者相等,則返回 a

適用於初始化列表 (3) 的版本返回列表中所有元素中最大的。如果有多個最大值,則返回第一個。

該函式使用operator<(如果提供了 comp,則使用 comp)來比較這些值。

此函式模板(C++98)的行為等同於
1
2
3
template <class T> const T& max (const T& a, const T& b) {
  return (a<b)?b:a;     // or: return comp(a,b)?b:a; for version (2)
}

引數

a, b
要比較的值。
comp
二元函式,接受兩個 T 型別的引數,並返回一個可轉換為 bool 的值。返回的值表示第一個引數中的元素是否被認為小於第二個引數。
該函式不得修改其任何引數。
這可以是函式指標或函式物件。
il
il
這些物件是從初始化列表宣告符自動構造的。

T 應支援與 operator< 的比較。
T 必須是可複製構造的。
對於(3)T 應為複製構造

返回值

作為引數傳遞的值中較大的一個。

示例

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

int main () {
  std::cout << "max(1,2)==" << std::max(1,2) << '\n';
  std::cout << "max(2,1)==" << std::max(2,1) << '\n';
  std::cout << "max('a','z')==" << std::max('a','z') << '\n';
  std::cout << "max(3.14,2.73)==" << std::max(3.14,2.73) << '\n';
  return 0;
}

輸出
max(1,2)==2
max(2,1)==2
max('a','z')==z
max(3.14,2.73)==3.14


複雜度

與元素數量減一相比是線性的(對於(1)(2) 是常數)。

異常

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

另見