std::min_element
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    | 在标头  <algorithm>定义 | ||
| (1) | ||
| template< class ForwardIt >  ForwardIt min_element( ForwardIt first, ForwardIt last ); | (C++17 前) | |
| template< class ForwardIt >  constexpr ForwardIt min_element( ForwardIt first, ForwardIt last ); | (C++17 起) | |
| template< class ExecutionPolicy, class ForwardIt >  ForwardIt min_element( ExecutionPolicy&& policy,  | (2) | (C++17 起) | 
| (3) | ||
| template< class ForwardIt, class Compare > ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp ); | (C++17 前) | |
| template< class ForwardIt, class Compare > constexpr ForwardIt min_element( ForwardIt first, ForwardIt last, | (C++17 起) | |
| template< class ExecutionPolicy, class ForwardIt, class Compare > ForwardIt min_element( ExecutionPolicy&& policy,  | (4) | (C++17 起) | 
寻找范围 [first, last) 中的最小元素。
1) 用 
operator< 比较元素。3) 用给定的二元比较函数 comp 比较元素。
2,4) 同 (1,3),但按照 policy 执行。这些重载只有在 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> (C++20 前)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> (C++20 起) 是 true 时才会参与重载决议。
参数
| first, last | - | 定义要检验范围的向前迭代器 | 
| policy | - | 所用的执行策略。细节见执行策略。 | 
| comp | - | 比较函数对象(即满足比较 (Compare) 要求的对象),如果 a小于b,那么返回 true。比较函数的签名应等价于如下: bool cmp(const Type1 &a, const Type2 &b); 虽然签名不必有 const & ,函数也不能修改传递给它的对象,而且必须接受(可有 const 限定的)类型  | 
| 类型要求 | ||
| - ForwardIt必须符合老式向前迭代器 (LegacyForwardIterator)  的要求。 | ||
返回值
指向范围 [first, last) 中最小元素的迭代器。如果范围中有多个元素等价于最小元素,那么返回指向首个这种元素的迭代器。范围为空时返回 last。
复杂度
准确比较 max(N-1,0) 次,其中 N = std::distance(first, last)。
异常
拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:
-  如果作为算法一部分调用的函数的执行抛出异常,且 ExecutionPolicy是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy,行为由实现定义。
- 如果算法无法分配内存,那么抛出 std::bad_alloc。
可能的实现
| 版本一 | 
|---|
| template<class ForwardIt> ForwardIt min_element(ForwardIt first, ForwardIt last) { if (first == last) return last; ForwardIt smallest = first; ++first; for (; first != last; ++first) if (*first < *smallest) smallest = first; return smallest; } | 
| 版本二 | 
| template<class ForwardIt, class Compare> ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp) { if (first == last) return last; ForwardIt smallest = first; ++first; for (; first != last; ++first) 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(std::begin(v), std::end(v)); std::cout << "最小元素位于:" << std::distance(std::begin(v), result); }
输出:
最小元素位于:1
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 | 
|---|---|---|---|
| LWG 212 | C++98 | first == last 时未指明返回值 | 此时返回 last | 
参阅
| 返回范围内的最大元素 (函数模板) | |
| (C++11) | 返回范围内的最小元素和最大元素 (函数模板) | 
| 返回各给定值中的较小者 (函数模板) |