std::min_element
定義於標頭檔案 <algorithm> |
||
template< class ForwardIt > ForwardIt min_element( ForwardIt first, ForwardIt last ); |
(1) | (自 C++17 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt > ForwardIt min_element( ExecutionPolicy&& policy, |
(2) | (C++17 起) |
template< class ForwardIt, class Compare > ForwardIt min_element( ForwardIt first, ForwardIt last, |
(3) | (自 C++17 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt, class Compare > ForwardIt min_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&,但函式不得修改傳遞給它的物件,並且必須能夠接受 |
型別要求 | ||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 |
[編輯] 返回值
指向範圍 [
first,
last)
中最小元素的迭代器。如果範圍中有多個元素等同於最小元素,則返回指向第一個此類元素的迭代器。如果範圍為空,則返回 last。
[編輯] 複雜度
給定 N 為 std::distance(first, last)
[編輯] 異常
帶有模板引數 ExecutionPolicy
的過載按如下方式報告錯誤
- 若演算法執行期間呼叫的函式丟擲異常且
ExecutionPolicy
為標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能的實現
min_element (1) |
---|
template<class ForwardIt> ForwardIt min_element(ForwardIt first, ForwardIt last) { if (first == last) return last; ForwardIt smallest = first; while (++first != last) if (*first < *smallest) smallest = first; return smallest; } |
min_element (3) |
template<class ForwardIt, class Compare> ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp) { if (first == last) return last; ForwardIt smallest = first; while (++first != last) if (comp(*first, *smallest)) smallest = first; return smallest; } |
[編輯] 示例
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v{3, 1, -4, 1, 5, 9}; std::vector<int>::iterator result = std::min_element(v.begin(), v.end()); std::cout << "min element has value " << *result << " and index [" << std::distance(v.begin(), result) << "]\n"; }
輸出
min element has value -4 and index [2]
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 212 | C++98 | 若 [ first, last) 為空,則未指定返回值。 |
在這種情況下返回 last |
LWG 2150 | C++98 | 返回了指向第一個非最大元素的迭代器 | 修正了返回值 |
[編輯] 另請參閱
返回一個範圍中最大的元素 (函式模板) | |
(C++11) |
返回範圍中最小和最大的元素 (函式模板) |
返回給定值中較小的那個 (函式模板) | |
(C++20) |
返回一個範圍中最小的元素 (演算法函式物件) |