std:: minmax
|
定义于头文件
<algorithm>
|
||
|
template
<
class
T
>
std:: pair < const T & , const T & > minmax ( const T & a, const T & b ) ; |
(1) |
(C++11 起)
(C++14 起为 constexpr) |
|
template
<
class
T,
class
Compare
>
std::
pair
<
const
T
&
,
const
T
&
>
minmax
(
const
T
&
a,
const
T
&
b,
|
(2) |
(C++11 起)
(C++14 起为 constexpr) |
|
template
<
class
T
>
std:: pair < T, T > minmax ( std:: initializer_list < T > ilist ) ; |
(3) |
(C++11 起)
(C++14 起为 constexpr) |
|
template
<
class
T,
class
Compare
>
std::
pair
<
T, T
>
minmax
(
std::
initializer_list
<
T
>
ilist,
|
(4) |
(C++11 起)
(C++14 起为 constexpr) |
返回给定值中的最小值和最大值。
目录 |
参数
| a, b | - | 要比较的值 |
| ilist | - | 包含待比较值的初始化列表 |
| comp | - |
比较函数对象(即满足
Compare
要求的对象),当第一个参数
小于
第二个参数时返回
true
。
比较函数的签名应等价于如下形式: bool cmp ( const Type1 & a, const Type2 & b ) ;
虽然签名不需要包含
const
&
,但函数不得修改传递的对象,且必须能够接受所有(可能为 const 的)
|
返回值
复杂度
| 3N |
| 2 |
| 3N |
| 2 |
可能的实现
| minmax (1) |
|---|
| minmax (2) |
| minmax (3) |
template<class T> constexpr std::pair<T, T> minmax(std::initializer_list<T> ilist) { auto p = std::minmax_element(ilist.begin(), ilist.end()); return std::pair(*p.first, *p.second); } |
| minmax (4) |
template<class T, class Compare> constexpr std::pair<T, T> minmax(std::initializer_list<T> ilist, Compare comp) { auto p = std::minmax_element(ilist.begin(), ilist.end(), comp); return std::pair(*p.first, *p.second); } |
注释
对于重载
(
1,2
)
,如果其中一个参数是临时对象,则返回的引用将在包含
minmax
调用的完整表达式结束时成为悬垂引用:
int n = 1; auto p = std::minmax(n, n + 1); int m = p.first; // 正确 int x = p.second; // 未定义行为 // 注意结构化绑定存在相同问题 auto [mm, xx] = std::minmax(n, n + 1); xx; // 未定义行为
示例
#include <algorithm> #include <cstdlib> #include <ctime> #include <iostream> #include <vector> int main() { std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6}; std::srand(std::time(0)); std::pair<int, int> bounds = std::minmax(std::rand() % v.size(), std::rand() % v.size()); std::cout << "v[" << bounds.first << "," << bounds.second << "]: "; for (int i = bounds.first; i < bounds.second; ++i) std::cout << v[i] << ' '; std::cout << '\n'; }
可能的输出:
v[2,7]: 4 1 5 9 2
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
| DR | 适用范围 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2239 | C++11 |
重载版本
(
2,4
)
要求
T
满足
LessThanComparable
要求
|
无需此要求 |
参见
|
返回给定值中的较小者
(函数模板) |
|
|
返回给定值中的较大者
(函数模板) |
|
|
(C++11)
|
返回范围中的最小和最大元素
(函数模板) |
|
(C++20)
|
返回两个元素中的较小者和较大者
(算法函数对象) |