std::min
ヘッダ <algorithm> で定義 | ||
(1) | ||
template<class T > const T& min(const T& a, const T& b ); | (C++14未満) | |
template<class T > constexprconst T& min(const T& a, const T& b ); | (C++14以上) | |
(2) | ||
template<class T, class Compare > const T& min(const T& a, const T& b, Compare comp ); | (C++14未満) | |
template<class T, class Compare > constexprconst T& min(const T& a, const T& b, Compare comp ); | (C++14以上) | |
(3) | ||
template<class T > T min(std::initializer_list<T> ilist ); | (C++11以上) (C++14未満) | |
template<class T > constexpr T min(std::initializer_list<T> ilist ); | (C++14以上) | |
(4) | ||
template<class T, class Compare > T min(std::initializer_list<T> ilist, Compare comp ); | (C++11以上) (C++14未満) | |
template<class T, class Compare > constexpr T min(std::initializer_list<T> ilist, Compare comp ); | (C++14以上) | |
指定された値の小さい方を返します。
a
と b
の小さい方を返します。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 の要件を満たさなければなりません。 |
[編集]戻り値
a
と b
の小さい方。 値が同等な場合は a
を返します。ilist
内の最も小さな値。 最も小さな同等な値が複数ある場合は、最も左のそのような値を返します。[編集]計算量
ilist.size() - 1
回の比較。[編集]実装例
1つめのバージョン |
---|
template<class T>const T& min(const T& a, const T& b){return(b < a)? b : a;} |
2つめのバージョン |
template<class T, class Compare>const T& min(const T& a, const T& b, Compare comp){return(comp(b, a))? b : a;} |
3つめのバージョン |
template<class T> T min(std::initializer_list<T> ilist){return*std::min_element(ilist.begin(), ilist.end());} |
4つめのバージョン |
template<class T, class Compare> T min(std::initializer_list<T> ilist, Compare comp){return*std::min_element(ilist.begin(), ilist.end(), comp);} |
[編集]警告
引数のいずれかが右辺値で、その引数が返された場合、 std::min
の結果を参照でキャプチャすると、ダングリング参照が生成されます。
int n =1;constint& r = std::min(n-1, n+1);// r はダングリングです。
[編集]例
#include <algorithm>#include <iostream>#include <string> int main(){std::cout<<"smaller of 1 and 9999: "<< std::min(1, 9999)<<'\n'<<"smaller of 'a', and 'b': "<< std::min('a', 'b')<<'\n'<<"shortest of \"foo\", \"bar\", and \"hello\": "<< std::min({"foo", "bar", "hello"}, [](conststd::string& s1, conststd::string& s2){return s1.size()< s2.size();})<<'\n';}
出力:
smaller of 1 and 9999: 1 smaller of 'a', and 'b': a shortest of "foo", "bar", and "hello": foo
[編集]関連項目
指定された値の大きい方を返します (関数テンプレート) | |
(C++11) | 2つの要素の小さい方と大きい方を返します (関数テンプレート) |
指定範囲の最も小さな要素を返します (関数テンプレート) | |
(C++17) | 値を境界値の間にクランプします (関数テンプレート) |