std::max
提供: cppreference.com
ヘッダ <algorithm> で定義 | ||
(1) | ||
template<class T > const T& max(const T& a, const T& b ); | (C++14未満) | |
template<class T > constexprconst T& max(const T& a, const T& b ); | (C++14以上) | |
(2) | ||
template<class T, class Compare > const T& max(const T& a, const T& b, Compare comp ); | (C++14未満) | |
template<class T, class Compare > constexprconst T& max(const T& a, const T& b, Compare comp ); | (C++14以上) | |
(3) | ||
template<class T > T max(std::initializer_list<T> ilist ); | (C++11以上) (C++14未満) | |
template<class T > constexpr T max(std::initializer_list<T> ilist ); | (C++14以上) | |
(4) | ||
template<class T, class Compare > T max(std::initializer_list<T> ilist, Compare comp ); | (C++11以上) (C++14未満) | |
template<class T, class Compare > constexpr T max(std::initializer_list<T> ilist, Compare comp ); | (C++14以上) | |
指定された値の大きい方を返します。
1-2)
a
と b
の大きい方を返します。3-4) 初期化子リスト
ilist
内の最も大きな値を返します。(1,3) のバージョンは値を比較するために operator< を使用し、 (2,4) のバージョンは指定された比較関数 comp
を使用します。
目次 |
[編集]引数
a, b | - | 比較する値 |
ilist | - | 比較する値を持つ初期化子リスト |
comp | - | a が b より小さい場合に true を返す、比較関数オブジェクト (Compare の要件を満たすオブジェクト)。比較関数のシグネチャは以下と同等であるべきです。 bool cmp(const Type1 &a, const Type2 &b); シグネチャが const& を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、値カテゴリに関わらず |
型の要件 | ||
-オーバロード (1,3) を使用するためには T は LessThanComparable の要件を満たさなければなりません。 | ||
-オーバロード (3,4) を使用するためには T は CopyConstructible の要件を満たさなければなりません。 |
[編集]戻り値
1-2)
a
と b
の大きい方。 同等な場合は a
を返します。3-4)
ilist
内の最も大きな値。 最も大きな同等な値が複数ある場合は、最も左の値を返します。[編集]計算量
1-2) ちょうど1回の比較。
3-4) ちょうど
ilist.size() - 1
回の比較。[編集]実装例
1つめのバージョン |
---|
template<class T>const T& max(const T& a, const T& b){return(a < b)? b : a;} |
2つめのバージョン |
template<class T, class Compare>const T& max(const T& a, const T& b, Compare comp){return(comp(a, b))? b : a;} |
3つめのバージョン |
template<class T > T max(std::initializer_list<T> ilist){return*std::max_element(ilist.begin(), ilist.end());} |
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;constint& r = std::max(n-1, n+1);// r is dangling
[編集]例
Run this code
#include <algorithm>#include <iostream>#include <string> int main(){std::cout<<"larger of 1 and 9999: "<< std::max(1, 9999)<<'\n'<<"larger of 'a', and 'b': "<< std::max('a', 'b')<<'\n'<<"longest of \"foo\", \"bar\", and \"hello\": "<< std::max({"foo", "bar", "hello"}, [](conststd::string& s1, conststd::string& s2){return s1.size()< s2.size();})<<'\n';}
出力:
larger of 1 and 9999: 9999 larger of 'a', and 'b': b longest of "foo", "bar", and "hello": hello
[編集]関連項目
指定された値の小さい方を返します (関数テンプレート) | |
(C++11) | 2つの要素の小さい方と大きい方を返します (関数テンプレート) |
指定範囲の最も大きな要素を返します (関数テンプレート) |