std:: max
|
ヘッダーで定義
<algorithm>
|
||
|
template
<
class
T
>
const T & max ( const T & a, const T & b ) ; |
(1) | (C++14以降 constexpr) |
|
template
<
class
T,
class
Compare
>
const T & max ( const T & a, const T & b, Compare comp ) ; |
(2) | (C++14以降 constexpr) |
|
template
<
class
T
>
T max ( std:: initializer_list < T > ilist ) ; |
(3) |
(C++11以降)
(C++14以降 constexpr) |
|
template
<
class
T,
class
Compare
>
T max ( std:: initializer_list < T > ilist, Compare comp ) ; |
(4) |
(C++11以降)
(C++14以降 constexpr) |
指定された値のうち大きい方を返します。
ilist.
size
(
)
がゼロの場合、または
T
が
CopyConstructible
でない場合、動作は未定義です。
目次 |
パラメータ
| a, b | - | 比較する値 |
| ilist | - | 比較する値を含む初期化子リスト |
| comp | - |
比較関数オブジェクト(すなわち
Compare
要件を満たすオブジェクト)。
true
を返す場合、
a
が
b
より
小さい
ことを示す。
比較関数のシグネチャは以下と同等であるべき: bool cmp ( const Type1 & a, const Type2 & b ) ;
シグネチャが
const
&
を持つ必要はないが、関数は渡されたオブジェクトを変更してはならず、
値カテゴリ
に関係なく型
|
戻り値
計算量
実装例
| max (1) |
|---|
template<class T> const T& max(const T& a, const T& b) { return (a < b) ? b : a; } |
| max (2) |
template<class T, class Compare> const T& max(const T& a, const T& b, Compare comp) { return (comp(a, b)) ? b : a; } |
| max (3) |
template<class T> T max(std::initializer_list<T> ilist) { return *std::max_element(ilist.begin(), ilist.end()); } |
| max (4) |
template<class T, class Compare> T max(std::initializer_list<T> ilist, Compare comp) { return *std::max_element(ilist.begin(), ilist.end(), comp); } |
注記
std::max
の結果を参照でキャプチャすると、一方のパラメータが一時オブジェクトであり、かつそのパラメータが返される場合、ダングリング参照が生成されます:
int n = -1; const int& r = std::max(n + 2, n * 2); // r はダングリング参照となる
例
#include <algorithm> #include <iomanip> #include <iostream> #include <string_view> int main() { auto longest = [](const std::string_view s1, const std::string_view s2) { return s1.size() < s2.size(); }; std::cout << "Larger of 69 and 96 is " << std::max(69, 96) << "\n" "Larger of 'q' and 'p' is '" << std::max('q', 'p') << "'\n" "Largest of 010, 10, 0X10, and 0B10 is " << std::max({010, 10, 0X10, 0B10}) << '\n' << R"(Longest of "long", "short", and "int" is )" << std::quoted(std::max({"long", "short", "int"}, longest)) << '\n'; }
出力:
Larger of 69 and 96 is 96 Larger of 'q' and 'p' is 'q' Largest of 010, 10, 0X10, and 0B10 is 16 Longest of "long", "short", and "int" is "short"
不具合報告
以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 281 | C++98 |
T
は
CopyConstructible
であることが要求されていた
オーバーロード ( 1,2 ) |
要求されない |
| LWG 2239 |
C++98
C++11 |
1.
T
は
LessThanComparable
であることが要求されていた
オーバーロード ( 2 ) (C++98) および ( 4 ) (C++11) 2. 計算量の要件が欠落していた |
1. 要求されない
2. 要件を追加 |
関連項目
|
与えられた値のうち小さい方を返す
(関数テンプレート) |
|
|
(C++11)
|
2つの要素のうち小さい方と大きい方を返す
(関数テンプレート) |
|
範囲内の最大要素を返す
(関数テンプレート) |
|
|
(C++17)
|
値を境界値のペアの間にクランプする
(関数テンプレート) |
|
(C++20)
|
与えられた値のうち大きい方を返す
(アルゴリズム関数オブジェクト) |