std::min_element
来自 zh.cppreference.net
| 定义于头文件 <algorithm>
|
||
template< class ForwardIt >
ForwardIt min_element( ForwardIt first, ForwardIt last );
|
(1) | (constexpr 起 C++17) |
template< class ExecutionPolicy, class ForwardIt >
ForwardIt min_element( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last );
|
(2) | (自 C++17) |
template< class ForwardIt, class Compare >
ForwardIt min_element( ForwardIt first, ForwardIt last,
Compare comp );
|
(3) | (constexpr 起 C++17) |
template< class ExecutionPolicy, class ForwardIt, class Compare >
ForwardIt min_element( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last,
Compare comp );
|
(4) | (自 C++17) |
在范围 [first, last) 中查找最小元素。
1) 使用
operator<(直至 C++20)std::less{}(自 C++20)。3) 使用比较函数
comp。2,4) 同 (1,3),但按照
policy。 这些重载仅当以下表达式的值为
true:
|
|
(直至 C++20) |
|
|
(自 C++20) |
参数
| first, last | - | 定义要检查的元素 范围 的迭代器对 |
| policy | - | 要使用的 执行策略 |
| comp | - | 比较函数对象(即满足 Compare 要求的对象),返回 true 如果第一个参数 小于 第二个。比较函数的签名应等价于以下内容:
虽然签名不需要有 |
| 类型要求 | ||
-ForwardIt 必须满足 LegacyForwardIterator 的要求。
| ||
返回值
指向范围 [first, last) 中最小的元素的迭代器。如果范围内有多个元素等价于最小元素,则返回指向第一个这样的元素的迭代器。如果范围为空,则返回 last。
复杂度
给定 N 为 std::distance(first, last):
1,2) 恰好 max(N-1,0) 次比较使用
operator<(直至 C++20)std::less{}(自 C++20)。3,4) 恰好 max(N-1,0) 次比较函数的应用
comp。异常
带有模板参数名 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++ 标准。
| DR | 应用于 | 已发布行为 | 正确行为 |
|---|---|---|---|
| LWG 212 | C++98 | 如果 [first, last) 为空,则未指定返回值
|
返回 last 在此情况下
|
| LWG 2150 | C++98 | 返回了指向第一个非最大元素的迭代器 | 更正了返回值 |
参阅
| 返回范围中的最大元素 (函数模板 & 算法函数对象) | |
(C++20) |
|
(C++11) |
返回范围中的最小和最大元素 (函数模板 & 算法函数对象) |
(C++20) |
|
| 返回给定值中的较小值 (函数模板 & 算法函数对象) | |
(C++20) |
|
(C++20) |
返回范围中的最小元素 (算法函数对象) |