std::max
來自 cppreference.com
定義於標頭檔案 <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) |
返回給定值中較大的一個。
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 cmp(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) 恰好 N-1 次應用比較函式 comp。
[編輯] 可能的實現
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 is dangling
[編輯] 示例
執行此程式碼
#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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 281 | C++98 | 過載 (1,2) 要求 T 必須是 CopyConstructible。 |
未要求 |
LWG 2239 | C++98 C++11 |
1. 過載 (2) (C++98) 和 (4) (C++11) 要求 T 必須是 LessThanComparable。2. 缺少複雜度要求 |
1. 不再要求 2. 添加了要求 |
[編輯] 參閱
返回給定值中較小的那個 (函式模板) | |
(C++11) |
返回兩個元素中較小和較大的一個 (函式模板) |
返回一個範圍中最大的元素 (函式模板) | |
(C++17) |
將值限制在邊界值對之間 (函式模板) |
(C++20) |
返回給定值中較大的那個 (演算法函式物件) |