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) |
返回给定值的最小和最大者。
T 不可小于比较 (LessThanComparable) ,那么行为未定义。T 不可小于比较 (LessThanComparable) ,那么行为未定义。目录 |
[编辑] 参数
| a, b | - | 要比较的值 |
| ilist | - | 拥有要比较的值的初始化器列表 |
| cmp | - | 比较函数对象(即满足比较 (Compare) 要求的对象),如果a 小于 b,则返回 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; // ok 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++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2239 | C++11 | 重载 (2,4) 中 T 需要可小于比较 (LessThanComparable)
|
不需要 |
[编辑] 参阅
| 返回给定值中较小者 (函数模板) | |
| 返回给定值中较大者 (函数模板) | |
| (C++11) |
返回范围中的最小元和最大元 (函数模板) |
| (C++20) |
返回两个元素间的较小者和较大者 (算法函数对象) |

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.
