通用工具(3)--輔助函式
阿新 • • 發佈:2018-12-28
挑選最大值和最小值
使用通用工具時候需要新增,用來在兩值或者多個值中選擇最大值和最小值。
舉例: 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");
}