std::min
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
template< class T > const T& min( const T& a, const T& b ); |
(1) | (C++14 起為 constexpr) |
template< class T, class Compare > const T& min( const T& a, const T& b, Compare comp ); |
(2) | (C++14 起為 constexpr) |
template< class T > T min( std::initializer_list<T> ilist ); |
(3) | (C++11 起) (C++14 起為 constexpr) |
template< class T, class Compare > T min( std::initializer_list<T> ilist, Compare comp ); |
(4) | (C++11 起) (C++14 起為 constexpr) |
返回給定值中較小的一個。
1,2) 返回 a 和 b 中較小的一個。
1) 使用 operator< 比較值。
若
T
不為 LessThanComparable,則行為未定義。2) 使用比較函式 comp 比較值。
3,4) 返回初始化器列表 ilist 中最小的值。
3) 使用 operator< 比較值。
若
T
不為 LessThanComparable,則行為未定義。4) 使用比較函式 comp 比較值。
目錄 |
[編輯] 引數
a, b | - | 要比較的值 |
ilist | - | 包含要比較值的初始化列表 |
comp | - | 比較函式物件(即滿足 Compare 要求的物件),若 a 小於 b 則返回 true。 比較函式的簽名應等效於以下內容 bool comp(const Type1& a, const Type2& b); 雖然簽名不需要有 const&,但函式不能修改傳遞給它的物件,並且必須能夠接受 |
[編輯] 返回值
1,2) a 和 b 中較小的一個。若值等價,則返回 a。
3,4) ilist 中最小的值。若有多個值與最小值等價,則返回最左側的那個值。
[編輯] 複雜度
1) 恰好一次使用 operator< 的比較。
2) 恰好一次比較函式 comp 的應用。
3,4) 給定 N 為 ilist.size()
3) 恰好使用 operator< 進行 N-1 次比較。
4) 恰好應用比較函式 comp N-1 次。
[編輯] 可能的實現
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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 281 | C++98 | 過載 (1,2) 要求 T 為 CopyConstructible |
未要求 |
LWG 2239 | C++98 C++11 |
1. 過載 (2) (C++98) 和 (4) (C++11) 要求 T 為 LessThanComparable2. 缺少複雜度要求 |
1. 不再要求 2. 增加了要求 |
[編輯] 參閱
返回給定值中較大的那個 (函式模板) | |
(C++11) |
返回兩個元素中較小和較大的一個 (函式模板) |
返回一個範圍中最小的元素 (函式模板) | |
(C++17) |
將值限制在邊界值對之間 (函式模板) |
(C++20) |
返回給定值中較小的那個 (演算法函式物件) |