C++11标准模板(STL) 您所在的位置:网站首页 自定义max函数的代码 C++11标准模板(STL)

C++11标准模板(STL)

2024-07-08 23:36| 来源: 网络整理| 查看: 265

定义于头文件

算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last) ,其中 last 指代要查询或修改的最后元素的后一个元素。

返回各给定值中的较大者 std::max

template< class T > const T& max( const T& a, const T& b );

(1)(C++14 前)

template< class T > constexpr const T& max( const T& a, const T& b );

(C++14 起)

template< class T, class Compare > const T& max( const T& a, const T& b, Compare comp );

(2)(C++14 前)

template< class T, class Compare > constexpr const T& max( const T& a, const T& b, Compare comp );

(C++14 起)

template< class T > T max( std::initializer_list ilist );

(3)(C++11 起) (C++14 前)

template< class T > constexpr T max( std::initializer_list ilist );

(C++14 起)

template< class T, class Compare > T max( std::initializer_list ilist, Compare comp );

(4)(C++11 起) (C++14 前)

template< class T, class Compare > constexpr T max( std::initializer_list ilist, Compare comp );

(C++14 起)

返回给定值中的较大者。

1-2) 返回 a 与 b 的较大者。

3-4) 返回 initializer_list ilist 中值的最大者。

(1,3) 版本用 operator< 比较元素, (2,4) 版本用给定的比较函数 comp 。

参数 a, b-要比较的值ilist-拥有要比较的值的 initializer_listcmp-比较函数对象(即满足比较 (Compare) 要求的对象),若若 a 小于 b ,则返回 ​true 。

比较函数的签名应等价于如下:

 bool cmp(const Type1 &a, const Type2 &b);

虽然签名不必有 const & ,函数也不能修改传递给它的对象,而且必须接受(可为 const 的)类型 Type1 与 Type2 的值,无关乎值类别(从而不允许 Type1 & ,亦不允许 Type1 ,除非 Type1 的移动等价于复制 (C++11 起))。 类型 Type1 与 Type2 必须使得 T 类型的对象能隐式转换到这两个类型。 ​

类型要求- 为使用重载 (1,3) , T 必须满足可小于比较 (LessThanComparable) 的要求。- 为使用重载 (3,4) , T 必须满足可复制构造 (CopyConstructible) 的要求。 返回值

1-2) a 与 b 的较大者。若它们等价,则返回 a 。

3-4) ilist 中的最大值。若有数个等价于最大者的值,则返回最左侧的这种值。

复杂度

1-2) 准确一次比较

3-4) 准确 ilist.size() - 1 次比较

可能的实现 版本一 template const T& max(const T& a, const T& b) { return (a < b) ? b : a; } 版本二 template const T& max(const T& a, const T& b, Compare comp) { return (comp(a, b)) ? b : a; } 版本三 template< class T > T max( std::initializer_list ilist) { return *std::max_element(ilist.begin(), ilist.end()); } 版本四 template< class T, class Compare > T max( std::initializer_list ilist, Compare comp ) { return *std::max_element(ilist.begin(), ilist.end(), comp); } 注意

若参数之一是右值,且返回该参数,则以引用捕获 std::max 的结果会产生一个悬垂引用:

int n = 1; const int& r = std::max(n-1, n+1); // r 为悬垂

调用示例 #include #include #include #include #include #include using namespace std; struct Cell { int x; int y; Cell &operator +=(const Cell &cell) { x += cell.x; y += cell.y; return *this; } bool operator


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有