std::max
来自 cppreference.cn
定义于头文件 <algorithm> |
||
template< class T > const T& max( const T& a, const T& b ); |
(1) | (constexpr since C++14) |
template< class T, class Compare > const T& max( const T& a, const T& b, Compare comp ); |
(2) | (constexpr since C++14) |
template< class T > T max( std::initializer_list<T> ilist ); |
(3) | (since C++11) (constexpr since C++14) |
template< class T, class Compare > T max( std::initializer_list<T> ilist, Compare comp ); |
(4) | (since C++11) (constexpr since C++14) |
返回给定值中较大的值。
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&,但该函数不得修改传递给它的对象,并且必须能够接受类型(可能是 const) |
[编辑] 返回值
1,2) a 和 b 中较大的值。如果它们相等,则返回 a。
3,4) ilist 中最大的值。如果多个值都等于最大值,则返回最左边的值。
[编辑] 复杂度
1) 恰好一次使用 operator< 的比较。
2) 恰好一次应用比较函数 comp。
3,4) 给定 N 为 ilist.size()
3) 恰好 N-1 次使用 operator< 的比较。
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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 281 | C++98 | 对于重载 (1,2),T 需要是 CopyConstructible |
不需要 |
LWG 2239 | C++98 C++11 |
1. 对于重载 (2) (C++98) 和 (4) (C++11),T 需要是 LessThanComparable重载 (2) (C++98) 和 (4) (C++11) 2. 缺少复杂度要求 |
1. 不需要 2. 添加了要求 |
[编辑] 参见
返回给定值中较小的值 (函数模板) | |
(C++11) |
返回两个元素中较小和较大的值 (函数模板) |
返回范围中最大的元素 (函数模板) | |
(C++17) |
将值钳制在一对边界值之间 (函数模板) |
(C++20) |
返回给定值中较大的值 (算法函数对象) |