c++标准库提供了若干小型辅助函数,用来挑选最小值,挑选最大值,交换两个值或者提供增补的比较操作符;
说明:
minmax() 返回一个pair<>,其中first是最小值,second是最大值;关于双参数版本,如果被比较的二值相等,min()和max()返回第一个元素;带(initlist)的版本,返回多个最小值或最大值中的第一个元素;两个参数版本返回的是个reference;接受(initlist)版本的返回被比较值的拷贝; template<typename T> const T& min(const T& a, cosnt T& b); template<typename T> T min(initializer_list<T> initlist);原因: 1. “initlist”版本,器内部需要一块临时空间,如果返回reference,返回的是一个空悬的reference;
说明: 1. 【c++11】:数值被moved或者move assigned 2. 以前是通过: assigned或copied,定义与头文件<algorithm>;
有四个function template 分别定义了!=,>,<=和>=,四个比较操作符;他们都是利用操作符==和<完成的,这四个函数定义与<utility>,定义如下;
// != template<tyname T> inline bool operator!=(const T& x, const T& y) { return !(x==y); } // > template<tyname T> inline bool operator>(const T& x, const T& y) { return (y<x); } //<= template<tyname T> inline bool operator<=(const T& x, const T& y) { return !(y<x); } //>= template<tyname T> inline bool operator>=(const T& x, const T& y) { return !(x<y); }说明: 1. 这四个操作符依赖于<和==,因此自己定义<和==; 2. 要使用这些操作符,使用using namespace std::rel_ops 例如:
class X{ public : bool operator==(cosnt X&x) const; bool operator<(const X& x) const; ... }; //... void foo() { using namespace std::rel_ops; //使用 !=,> ,>=,<= X x1,x2; .. if(x1!=x2){...} //ok }