std::min
ja.cppreference.net より
| ヘッダ <algorithm>
|
||
template< class T >
const T& min( const T& a, const T& b );
|
で定義 (1) | (constexpr C++14 以降) |
template< class T, class Compare >
const T& min( const T& a, const T& b, Compare comp );
|
(2) | (constexpr C++14 以降) |
template< class T >
T min( std::initializer_list<T> ilist );
|
(3) | (C++11 以降) (constexpr C++14 以降) |
template< class T, class Compare >
T min( std::initializer_list<T> ilist, Compare comp );
|
(4) | (C++11 以降) (constexpr C++14 以降) |
与えられた値のうち小さい方を返す。
1,2)
a と b の小さい方を返す。1)
operator< を使用して値を比較する。T が LessThanComparable でない場合、動作は未定義である。2) 比較関数
comp を使用して値を比較する。3,4) 初期化子リスト
ilist 内の値のうち最小のものを返す。3)
operator< を使用して値を比較する。T が LessThanComparable でない場合、動作は未定義である。4) 比較関数
comp を使用して値を比較する。引数
| a, b | - | 比較する値 |
| ilist | - | 比較する値を含む初期化子リスト |
| cmp | - | 比較関数オブジェクト (つまり Compare の要件を満たすオブジェクト) であり、true が a より 小さい 場合に b を返す。比較関数のシグネチャは以下と同等であるべきである:
シグネチャに |
戻り値
1,2)
a と b の小さい方。値が等価な場合は、a を返す。3,4)
ilist 内の最小値。複数の値が最小値と等価な場合は、最も左にある値を返す。計算量
1)
operator< を使用した比較がちょうど 1 回。2) 比較関数
comp の適用がちょうど 1 回。3,4) N を
ilist.size() として:3) N-1 回の
operator< を使用した比較。4) N-1 回の比較関数
comp の適用。実装例
| min (1) |
|---|
template<class T>
const T& min(const T& a, const T& b)
{
return (b < a) ? b : a;
}
|
| min (2) |
template<class T, class Compare>
const T& min(const T& a, const T& b, Compare comp)
{
return (comp(b, a)) ? b : a;
}
|
| min (3) |
template<class T>
T min(std::initializer_list<T> ilist)
{
return *std::min_element(ilist.begin(), ilist.end());
}
|
| min (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;
const int& r = std::min(n + 2, n * 2); // r is dangling
例
このコードを実行
#include <algorithm>
#include <iostream>
#include <string_view>
int main()
{
std::cout << "smaller of 10 and 010 is " << std::min(10, 010) << '\n'
<< "smaller of 'd' and 'b' is '" << std::min('d', 'b') << "'\n"
<< "shortest of \"foo\", \"bar\", and \"hello\" is \""
<< std::min({"foo", "bar", "hello"},
[](const std::string_view s1, const std::string_view s2)
{
return s1.size() < s2.size();
}) << "\"\n";
}
出力:
smaller of 10 and 010 is 8
smaller of 'd' and 'b' is 'b'
shortest of "foo", "bar", and "hello" is "foo"
欠陥報告
以下の動作を変更する欠陥報告は、以前に公開された C++ 標準に遡って適用された。
| DR | 適用先 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 281 | C++98 | TT はオーバーロード (CopyConstructible に対して ((1,2)
|
必要とされた) 必要なかった |
| LWG 2239 | C++98 C++11 |
1. T はオーバーロード (LessThanComparable に対して (オーバーロード ((2) (C++98) および ((4) (C++11) 2. 計算量の要件が欠落していた |
1. 不要になった 2. 要件を追加 |
関連項目
| 与えられた値のうち大きい方を返す (関数テンプレート & アルゴリズム関数オブジェクト) | |
(C++20) |
|
(C++11) |
2 つの要素の小さい方と大きい方を返す (関数テンプレート & アルゴリズム関数オブジェクト) |
(C++20) |
|
| 範囲内の最小の要素を返す (関数テンプレート & アルゴリズム関数オブジェクト) | |
(C++20) |
|
(C++17) |
値を一対の境界値の間にクランプする (関数テンプレート & アルゴリズム関数オブジェクト) |
(C++20) |
|
(C++20) |
与えられた値のうち小さい方を返す (アルゴリズム関数オブジェクト) |