通用工具(3)--辅助函数

挑选最大值和最小值

使用通用工具时候需要添加,用来在两值或者多个值中选择最大值和最小值。
举例: std::min();判断最小值

min(a,b) //返回a和b的最小值
min(a,b,cmp)//通过cmp比较a与b
min(intlist)//返回初值列的最小值
min(intlist,cmp)//通过cmp比较初值列

其中cmp是一个函数或者函数对象,但是必须是bool cmp(T x,T y)的函数。

		// TEMPLATE FUNCTION min WITH PRED
template<class _Ty,
	class _Pr> inline
	constexpr const _Ty& (min)(const _Ty& _Left, const _Ty& _Right,
		_Pr _Pred)
		_NOEXCEPT_OP(_NOEXCEPT_OP(_DEBUG_LT_PRED(_Pred, _Right, _Left)))
	{	// return smaller of _Left and _Right using _Pred
	return (_DEBUG_LT_PRED(_Pred, _Right, _Left) ? _Right : _Left);
	}

我们可以看中的源码,其返回值是一个条件运算符。cmp函数会返回一个布尔值,如果为true返回第二个参数的值,否者返回第一个参数的值

bool int_ptr_less(int a, int b)
{

	return (a*10)<(b*5);
}

c = std::min(9, 20,int_ptr_less );//结果返回9
c = std::min(30, 20,int_ptr_less );//结果返回30;

你也可以通过lambda函数使用

int c = std::min({ 1,2,3 }, [](int a, int b) {return a > b; });//true返回第二个参数,false返回第一个参数

所以带cmp的辅助函数我们可以通过制定规则得到想要的结果
除了min还有max,minmax等

max(a,b) //返回a和b的最大值
max(a,b,cmp)//通过cmp比较a与b
max(intlist)//返回初值列的最大值
max(intlist,cmp)//通过cmp比较初值列
minmax(a,b) //返回a和b的最大值
minmax(a,b,cmp)//通过cmp比较a与b
minmax(intlist)//返回初值列的最小值最大值
minmax(intlist,cmp)//通过cmp比较初值列

注意:
1,minmax返回一个pair,第一个值为最小值,第二个值为最大值
2,接受两个值返回值是引用,而初值列的是拷贝
3,要求两个实参的类型必须相同

namespace std{
 template <typename T>
 const T& min(const T& a,const T& b);
  template <typename T>
 T min(initializer_list<T> initlist);
}

两值互换swap

swap定义于,用于交换两个对象的值
与之前的变化,由copy语义变为move语义

namespace std{
template <typename T>
inline void swap(T& a,T& b)
   {
      T tmp(std::move(a));
      a=std::move(b);
      b=std::move(tmp); 
   }
}

swap的优势在于通过模版化或者函数重载,进行复杂的类型或者对象进行交换,通过交换对象的成员进行而不是通过对对象的赋值。如下,对一个简单的对象swap。

    class test
    {
       private:
         int * p;
         int num;
       public:
         void swap(test & x)
         {
           std::swap(p,x.p);
           std::swap(num,x.num);
         }
    }

增补的比较操作符

增补的比较操作符定义于中,用4个函数模版分别定义了!=,>,<=,>=,他们都是通过<和= =实现的。

// !=
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);
}

只需要定义好<和==就可以使用他们,当然也可以写好using namespace std::rel_ops,这样显示得更简单一点

#include<iostream>
#include<algorithm>
#include<utility>
using namespace std;

class X
{
private:
	int x;
	
public:
	X(int x_)
	{
		x = x_;
	}
	bool operator<(const X& y)const
	{
		return x < y.x;
	}
	bool operator==(const X& y)const
	{
		return x == y.x;
	}
};
int main()
{
	X x1(10);
	X x2(20);
	std::rel_ops::operator<=(x1, x2);
	std::rel_ops::operator>(x1, x2);
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/qq_35651984/article/details/84729264