std::ranges::max
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    |   定义于头文件  <algorithm>
  | 
||
|   调用签名  | 
||
|   template< class T, class Proj = std::identity,           std::indirect_strict_weak_order<  | 
(C++20 起) | |
|   template< class T, class Proj = std::identity,           std::indirect_strict_weak_order<  | 
(C++20 起) | |
|   template< ranges::input_range R, class Proj = std::identity,           std::indirect_strict_weak_order<  | 
(C++20 起) | |
返回给定的被投影值的较大者。
1) 返回 
a 与 b 的较大者。2) 返回 initializer_list 
r 中的首个最大值。3) 返回范围 
r 中的首个最大值。此页面上描述的仿函数实体是 niebloid ,即:
实际上,它们能以函数对象,或以某些特殊编译器扩展实现。
参数
| a, b | - | 要比较的值 | 
| r | - | 要比较的值的范围 | 
| comp | - | 应用到投影后元素的比较 | 
| proj | - | 应用到元素的投影 | 
返回值
1) 
a 与 b 的较大值,按照其各自的被投影值。若它们等价则返回 a 。2-3) 
r 中按照投影的最大值。若数个值等价于最大值,则返回最左者。若范围为空(由 ranges::distance(r) 确定)则行为未定义。复杂度
1) 准确比较一次。
2-3) 准确比较 ranges::distance(r) - 1 次。
可能的实现
struct max_fn { template<class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr const T& operator()(const T& a, const T& b, Comp comp = {}, Proj proj = {}) const { return std::invoke(comp, std::invoke(proj, a), std::invoke(proj, b)) ? b : a; } template<class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr const T& operator()(std::initializer_list<T> r, Comp comp = {}, Proj proj = {}) const { return *ranges::max_element(r, std::ref(comp), std::ref(proj)); } template<ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*> constexpr ranges::range_value_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return *ranges::max_element(r, std::ref(comp), std::ref(proj)); } }; inline constexpr max_fn max;  | 
注解
若参数之一是临时量,而该参数被返回,则以引用捕获 std::ranges::max 的结果会产生一个悬垂引用:
int n = 1; const int& r = std::ranges::max(n-1, n+1); // r 悬垂
示例
运行此代码
#include <algorithm> #include <iostream> #include <string> int main() { namespace ranges = std::ranges; using namespace std::string_view_literals; std::cout << "larger of 1 and 9999: " << ranges::max(1, 9999) << '\n' << "larger of 'a', and 'b': '" << ranges::max('a', 'b') << "'\n" << "longest of \"foo\", \"bar\", and \"hello\": \"" << ranges::max({ "foo"sv, "bar"sv, "hello"sv }, {}, &std::string_view::size) << "\"\n"; }
输出:
larger of 1 and 9999: 9999 larger of 'a', and 'b': 'b' longest of "foo", "bar", and "hello": "hello"
参阅
|    (C++20)  | 
  返回给定值的较小者  (niebloid)  | 
|    (C++20)  | 
  返回两个元素的较小和较大者  (niebloid)  | 
|    (C++20)  | 
  返回范围中的最大元素  (niebloid)  | 
|    (C++20)  | 
   在一对边界值间夹一个值  (niebloid)  | 
|    返回各给定值中的较大者   (函数模板)  |