std::max_element
定义于头文件 <algorithm> |
||
template< class ForwardIt > ForwardIt max_element( ForwardIt first, ForwardIt last ); |
(1) | (constexpr since C++17) |
template< class ExecutionPolicy, class ForwardIt > ForwardIt max_element( ExecutionPolicy&& policy, |
(2) | (since C++17) |
template< class ForwardIt, class Compare > ForwardIt max_element( ForwardIt first, ForwardIt last, |
(3) | (constexpr since C++17) |
template< class ExecutionPolicy, class ForwardIt, class Compare > ForwardIt max_element( ExecutionPolicy&& policy, |
(4) | (since C++17) |
在范围 [
first,
last)
中查找最大元素。
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 为 true。 |
(C++20 前) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> 为 true。 |
(C++20 起) |
内容 |
[编辑] 参数
first, last | - | 定义要检查的元素范围的迭代器对 |
policy | - | 要使用的执行策略 |
comp | - | 比较函数对象(即,满足比较 (Compare) 要求的对象),如果第一个参数小于第二个参数,则返回 true。 比较函数的签名应等效于以下内容 bool cmp(const Type1& a, const Type2& b); 虽然签名不需要具有 const&,但该函数不得修改传递给它的对象,并且必须能够接受类型(可能是 const) |
类型要求 | ||
-ForwardIt 必须满足遗留向前迭代器 (LegacyForwardIterator) 的要求。 |
[编辑] 返回值
指向范围 [
first,
last)
中最大元素的迭代器。如果范围内有多个元素等效于最大元素,则返回指向第一个此类元素的迭代器。如果范围为空,则返回 last。
[编辑] 复杂度
给定 N 作为 std::distance(first, last)
[编辑] 异常
具有名为 ExecutionPolicy
的模板参数的重载按如下方式报告错误
- 如果作为算法一部分调用的函数的执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用 std::terminate。对于任何其他ExecutionPolicy
,行为是实现定义的。 - 如果算法无法分配内存,则抛出 std::bad_alloc。
[编辑] 可能的实现
max_element (1) |
---|
template<class ForwardIt> ForwardIt max_element(ForwardIt first, ForwardIt last) { if (first == last) return last; ForwardIt largest = first; while (++first != last) if (*largest < *first) largest = first; return largest; } |
max_element (3) |
template<class ForwardIt, class Compare> ForwardIt max_element(ForwardIt first, ForwardIt last, Compare comp) { if (first == last) return last; ForwardIt largest = first; while(++first != last) if (comp(*largest, *first)) largest = first; return largest; } |
[编辑] 示例
#include <algorithm> #include <cmath> #include <iostream> #include <vector> int main() { std::vector<int> v{3, 1, -14, 1, 5, 9, -14, 9}; std::vector<int>::iterator result; result = std::max_element(v.begin(), v.end()); std::cout << "Max element found at index " << std::distance(v.begin(), result) << " has value " << *result << '\n'; result = std::max_element(v.begin(), v.end(), [](int a, int b) { return std::abs(a) < std::abs(b); }); std::cout << "Absolute max element found at index " << std::distance(v.begin(), result) << " has value " << *result << '\n'; }
输出
Max element found at index 5 has value 9 Absolute max element found at index 2 has value -14
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 212 | C++98 | 如果 [ first, last) 为空,则未指定返回值 |
在这种情况下返回 last |
LWG 2150 | C++98 | 返回指向第一个非最小元素的迭代器 | 更正了返回值 |
[编辑] 参见
返回范围中最小的元素 (函数模板) | |
(C++11) |
返回范围中最小和最大的元素 (函数模板) |
返回给定值中较大的值 (函数模板) | |
(C++20) |
返回范围中最大的元素 (算法函数对象) |