std::ranges::min
来自cppreference.com
在标头 <algorithm> 定义
|
||
调用签名 |
||
template< class T, class Proj = std::identity, std::indirect_strict_weak_order< |
(1) | (C++20 起) |
template< std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< |
(2) | (C++20 起) |
template< ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< |
(3) | (C++20 起) |
返回给定的投影后值的较小者。
1) 返回 a 与 b 的较小者。
2) 返回初始化列表 r 的首个最小元素。
3) 返回范围 r 中的首个最小值。
此页面上描述的函数式实体是 niebloid,即:
实践中,可以作为函数对象,或者用某些特殊编译器扩展实现它们。
参数
a, b | - | 要比较的对象 |
r | - | 要比较的元素的范围 |
comp | - | 应用到投影后元素的比较 |
proj | - | 应用到元素的投影 |
返回值
1) a 与 b 的根据投影的较小者。若它们等价,则返回 a。
2,3) r 中根据投影的最小元素。若有数个值等价于最小者,则返回最左的元素。若范围为空(由 ranges::distance(r) 确定)则行为未定义。若范围为空(由 ranges::distance(r) 确定),则其行为未定义。
复杂度
1) 准确比较一次。
2,3) 准确比较
ranges::distance(r) - 1
次。可能的实现
struct min_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, b), std::invoke(proj, a)) ? b : a; } template<std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr T operator()(std::initializer_list<T> r, Comp comp = {}, Proj proj = {}) const { return *ranges::min_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 { using V = ranges::range_value_t<R>; if constexpr (ranges::forward_range<R>) return static_cast<V>(*ranges::min_element(r, std::ref(comp), std::ref(proj))); else { auto i = ranges::begin(r); auto s = ranges::end(r); V m(*i); while (++i != s) if (std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, m))) m = *i; return m; } } }; inline constexpr min_fn min; |
注解
如果参数之一是临时量,而该参数被返回,那么以引用捕获 std::ranges::min
的结果会产生一个悬垂引用:
int n = 1; const int& r = std::ranges::min(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 << "smaller of 1 and 9999: " << ranges::min(1, 9999) << '\n' << "smaller of 'a', and 'b': '" << ranges::min('a', 'b') << "'\n" << "shortest of \"foo\", \"bar\", and \"hello\": \"" << ranges::min({"foo"sv, "bar"sv, "hello"sv}, {}, &std::string_view::size) << "\"\n"; }
输出:
smaller of 1 and 9999: 1 smaller of 'a', and 'b': 'a' shortest of "foo", "bar", and "hello": "foo"
参阅
(C++20) |
返回给定值的较大者 (niebloid) |
(C++20) |
返回两个元素的较小和较大者 (niebloid) |
(C++20) |
返回范围中的最小元素 (niebloid) |
(C++20) |
在一对边界值间夹一个值 (niebloid) |
返回各给定值中的较小者 (函数模板) |