std::min_element() 算法
- 自 C++17 起
- C++17 之前
template< class ForwardIt >
ForwardIt min_element( ForwardIt first, ForwardIt last );
// (2)
template< class ForwardIt, class Compare >
ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp );
// (3)
template< class ExecutionPolicy, class ForwardIt >
ForwardIt min_element( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last );
// (4)
template< class ExecutionPolicy, class ForwardIt, class Compare >
ForwardIt min_element( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, Compare comp );
template< class ForwardIt >
ForwardIt min_element( ForwardIt first, ForwardIt last );
// (2)
template< class ForwardIt, class Compare >
ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp );
查找范围 [first
; last
) 中最小的元素。
-
(1) 元素使用
operator<
进行比较。 -
(2) 元素使用给定的二元比较函数
comp
进行比较。
参数
first last | 查找最小元素的范围。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
comp | 比较函数对象(即满足 Compare 要求的对象)。比较函数的签名应等同于以下内容:
|
类型要求
RandomIt | LegacyRandomAccessIterator |
返回值
指向范围 [first
; last
) 中最大元素的迭代器。
如果范围中有多个元素与最大元素等价,则返回指向第一个此类元素的迭代器。
如果范围为空,则返回 last
。
复杂度
给定 N
为 std::distance(first, last)
精确比较 min(N - 1, 0)
次。
异常
带有模板参数 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;
++first;
for (; first != last; ++first)
if (*first < *smallest)
smallest = first;
return smallest;
}
min_element(2)
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;
}
示例
Main.cpp
#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]