std::minmax_element
定义于头文件 <algorithm> |
||
template< class ForwardIt > std::pair<ForwardIt, ForwardIt> |
(1) | (C++11 起) (constexpr C++17 起) |
template< class ExecutionPolicy, class ForwardIt > std::pair<ForwardIt, ForwardIt> |
(2) | (C++17 起) |
template< class ForwardIt, class Compare > std::pair<ForwardIt, ForwardIt> |
(3) | (C++11 起) (constexpr C++17 起) |
template< class ExecutionPolicy, class ForwardIt, class Compare > std::pair<ForwardIt, ForwardIt> |
(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 | - | 要使用的执行策略 |
cmp | - | 比较函数对象 (即,满足 Compare 要求的对象),如果第一个参数小于第二个参数,则返回 true。 比较函数的签名应等效于以下内容 bool cmp(const Type1& a, const Type2& b); 虽然签名不需要具有 const&,但该函数不得修改传递给它的对象,并且必须能够接受类型为(可能为 const) |
类型要求 | ||
-ForwardIt 必须满足 LegacyForwardIterator 的要求。 |
[编辑] 返回值
一个pair,由指向最小元素的迭代器作为第一个元素,指向最大元素的迭代器作为第二个元素组成。如果范围为空,则返回 std::make_pair(first, first)。如果多个元素等效于最小元素,则返回指向第一个此类元素的迭代器。如果多个元素等效于最大元素,则返回指向最后一个此类元素的迭代器。
[编辑] 复杂度
给定 N 为 std::distance(first, last)
3 |
2 |
[编辑] 异常
具有名为 ExecutionPolicy
的模板参数的重载按如下方式报告错误
- 如果作为算法一部分调用的函数的执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用 std::terminate。对于任何其他ExecutionPolicy
,行为是实现定义的。 - 如果算法无法分配内存,则会抛出 std::bad_alloc。
[编辑] 可能的实现
minmax_element |
---|
template<class ForwardIt> std::pair<ForwardIt, ForwardIt> minmax_element(ForwardIt first, ForwardIt last) { using value_type = typename std::iterator_traits<ForwardIt>::value_type; return std::minmax_element(first, last, std::less<value_type>()); } |
minmax_element |
template<class ForwardIt, class Compare> std::pair<ForwardIt, ForwardIt> minmax_element(ForwardIt first, ForwardIt last, Compare comp) { auto min = first, max = first; if (first == last || ++first == last) return {min, max}; if (comp(*first, *min)) min = first; else max = first; while (++first != last) { auto i = first; if (++first == last) { if (comp(*i, *min)) min = i; else if (!(comp(*i, *max))) max = i; break; } else { if (comp(*first, *i)) { if (comp(*first, *min)) min = first; if (!(comp(*i, *max))) max = i; } else { if (comp(*i, *min)) min = i; if (!(comp(*first, *max))) max = first; } } } return {min, max}; } |
[编辑] 注意
此算法与 std::make_pair(std::min_element(), std::max_element()) 不同,不仅在于效率,还在于此算法找到最后一个最大元素,而 std::max_element 找到第一个最大元素。
[编辑] 示例
#include <algorithm> #include <iostream> int main() { const auto v = {3, 9, 1, 4, 2, 5, 9}; const auto [min, max] = std::minmax_element(begin(v), end(v)); std::cout << "min = " << *min << ", max = " << *max << '\n'; }
输出
min = 1, max = 9
[编辑] 参见
返回范围中的最小元素 (函数模板) | |
返回范围中的最大元素 (函数模板) | |
(C++20) |
返回范围中最小和最大的元素 (算法函数对象) |