std::max() 算法
- 自 C++14 起
- 自 C++11 起
- 直到 C++11
// (1)
template< class T >
constexpr const T& max( const T& a, const T& b );
// (2)
template< class T, class Compare >
constexpr const T& max( const T& a, const T& b, Compare comp );
// (3)
template< class T >
constexpr T max( std::initializer_list<T> ilist );
// (4)
template< class T, class Compare >
constexpr T max( std::initializer_list<T> ilist, Compare comp );
// (1)
template< class T >
const T& max( const T& a, const T& b );
// (2)
template< class T, class Compare >
const T& max( const T& a, const T& b, Compare comp );
// (3)
template< class T >
T max( std::initializer_list<T> ilist );
// (4)
template< class T, class Compare >
T max( std::initializer_list<T> ilist, Compare comp );
// (1)
template< class T >
const T& max( const T& a, const T& b );
// (2)
template< class T, class Compare >
const T& max( const T& a, const T& b, Compare comp );
返回给定值中较大的一个。
- (1 - 2) 返回
a
和b
中较大的一个。 - (3 - 4) 返回初始化列表
ilist
中最大的值。
参数
a b | 要比较的值。 |
ilist | 包含要比较值的初始化列表。 |
cmp | 比较函数对象(即满足Compare要求的对象),如果
虽然签名不需要有
|
类型要求
-
(1, 3):
T
LessThanComparable -
(3 - 4):
T
CopyConstructible
返回值
- (1 - 2) 根据投影,
a
和b
中较大的一个。如果它们相等,则返回a
。 - (3 - 4)
ilist
中最大的值。如果多个值与最大值相等,则返回最左边的一个。
复杂度
- (1 - 2) 恰好一次比较。
- (3 - 4) 精确执行
ilist.size() - 1
次比较。
异常
(无)
可能的实现
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 - 1, n + 1); // r is dangling
示例
Main.cpp
#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"