std::minmax_element
定義於標頭檔案 <algorithm> |
||
template< class ForwardIt > std::pair<ForwardIt, ForwardIt> |
(1) | (C++11 起) (自 C++17 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt > std::pair<ForwardIt, ForwardIt> |
(2) | (C++17 起) |
template< class ForwardIt, class Compare > std::pair<ForwardIt, ForwardIt> |
(3) | (C++11 起) (自 C++17 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt, class Compare > std::pair<ForwardIt, ForwardIt> |
(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 | - | 要使用的 執行策略 |
cmp | - | 比較函式物件(即滿足 Compare 要求的物件),如果第一個引數小於第二個引數,則返回 true。 比較函式的簽名應等效於以下內容 bool cmp(const Type1& a, const Type2& b); 儘管簽名不需要包含 const&,但函式不得修改傳入的物件,並且必須能夠接受 |
型別要求 | ||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 |
[編輯] 返回值
一個對,其第一個元素是指向最小元素的迭代器,第二個元素是指向最大元素的迭代器。如果範圍為空,則返回 std::make_pair(first, first)。如果多個元素等價於最小元素,則返回指向第一個此類元素的迭代器。如果多個元素等價於最大元素,則返回指向最後一個此類元素的迭代器。
[編輯] 複雜度
給定 N 為 std::distance(first, last)
3 |
2 |
[編輯] 異常
帶有模板引數 ExecutionPolicy
的過載按如下方式報告錯誤
- 如果作為演算法一部分呼叫的函式執行丟擲異常,並且
ExecutionPolicy
是 標準策略 之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能的實現
minmax_element |
---|
template<class ForwardIt> std::pair<ForwardIt, ForwardIt> minmax_element(ForwardIt first, ForwardIt last) { using value_type = typename std::iterator_traits<ForwardIt>::value_type; return std::minmax_element(first, last, std::less<value_type>()); } |
minmax_element |
template<class ForwardIt, class Compare> std::pair<ForwardIt, ForwardIt> minmax_element(ForwardIt first, ForwardIt last, Compare comp) { auto min = first, max = first; if (first == last || ++first == last) return {min, max}; if (comp(*first, *min)) min = first; else max = first; while (++first != last) { auto i = first; if (++first == last) { if (comp(*i, *min)) min = i; else if (!(comp(*i, *max))) max = i; break; } else { if (comp(*first, *i)) { if (comp(*first, *min)) min = first; if (!(comp(*i, *max))) max = i; } else { if (comp(*i, *min)) min = i; if (!(comp(*first, *max))) max = first; } } } return {min, max}; } |
[編輯] 注意
此演算法與 std::make_pair(std::min_element(), std::max_element()) 不同,不僅在效率上,還在於此演算法找到最後一個最大元素,而 std::max_element 找到第一個最大元素。
[編輯] 示例
#include <algorithm> #include <iostream> int main() { const auto v = {3, 9, 1, 4, 2, 5, 9}; const auto [min, max] = std::minmax_element(begin(v), end(v)); std::cout << "min = " << *min << ", max = " << *max << '\n'; }
輸出
min = 1, max = 9
[編輯] 參閱
返回一個範圍中最小的元素 (函式模板) | |
返回一個範圍中最大的元素 (函式模板) | |
(C++20) |
返回範圍中最小和最大的元素 (演算法函式物件) |