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 | - |
比较函数对象(即满足比较要求),当第一个参数
小于
第二个时返回
true
。
比较函数的签名应等价于: bool cmp ( const Type1 & a, const Type2 & b ) ;
虽然签名不需要包含
const
&
,但函数不得修改传递给它的对象,且必须能够接受所有(可能为 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)
|
返回范围内的最小元素
(算法函数对象) |