std::max_element
定義於標頭檔案 <algorithm> |
||
template< class ForwardIt > ForwardIt max_element( ForwardIt first, ForwardIt last ); |
(1) | (自 C++17 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt > ForwardIt max_element( ExecutionPolicy&& policy, |
(2) | (C++17 起) |
template< class ForwardIt, class Compare > ForwardIt max_element( ForwardIt first, ForwardIt last, |
(3) | (自 C++17 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt, class Compare > ForwardIt max_element( ExecutionPolicy&& policy, |
(4) | (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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 212 | C++98 | 如果 [ first, last) 為空,則返回值未指定 |
在這種情況下返回 last |
LWG 2150 | C++98 | 返回了指向第一個非最小元素的迭代器 | 已更正返回值 |
[編輯] 另請參閱
返回一個範圍中最小的元素 (函式模板) | |
(C++11) |
返回範圍中最小和最大的元素 (函式模板) |
返回給定值中較大的那個 (函式模板) | |
(C++20) |
返回一個範圍中最大的元素 (演算法函式物件) |