std::ranges::max_element
来自 cppreference.cn
定义于头文件 <algorithm> |
||
调用签名 |
||
template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less > |
(1) | (since C++20) |
template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< |
(2) | (since C++20) |
1) 查找范围
[
first,
last)
内的最大元素。此页面上描述的类似函数的实体是算法函数对象(非正式地称为 niebloids),即
目录 |
[编辑] 参数
first, last | - | 定义要检查的元素范围的迭代器-哨位对 |
r | - | 要检查的 range |
comp | - | 应用于投影元素的比较 |
proj | - | 应用于元素的投影 |
[编辑] 返回值
指向范围 [
first,
last)
内最大元素的迭代器。如果范围内有多个元素等效于最大元素,则返回指向第一个此类元素的迭代器。如果范围为空(即,如果 first == last),则返回 last。
[编辑] 复杂度
恰好 max(N - 1, 0) 次比较,其中 N = ranges::distance(first, last)。
[编辑] 可能的实现
struct max_element_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { if (first == last) return last; auto largest = first; while (++first != last) if (std::invoke(comp, std::invoke(proj, *largest), std::invoke(proj, *first))) largest = first; return largest; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr max_element_fn max_element; |
[编辑] 示例
运行此代码
#include <algorithm> #include <cmath> #include <iostream> int main() { namespace ranges = std::ranges; const auto v = {3, 1, -14, 1, 5, 9, -14, 9}; auto result = ranges::max_element(v.begin(), v.end()); std::cout << "Max element at pos " << ranges::distance(v.begin(), result) << '\n'; auto abs_compare = [](int a, int b) { return std::abs(a) < std::abs(b); }; result = ranges::max_element(v, abs_compare); std::cout << "Absolute max element at pos " << ranges::distance(v.begin(), result) << '\n'; }
输出
Max element at pos 5 Absolute max element at pos 2
[编辑] 参见
(C++20) |
返回范围内的最小元素 (算法函数对象) |
(C++20) |
返回范围内的最小和最大元素 (算法函数对象) |
(C++20) |
返回给定值中较大的值 (算法函数对象) |
返回范围内的最大元素 (函数模板) |