天天看點

綁定取反擴充卡基本用法.cpp

《C++STL基礎及應用》
#include <iostream>
#include<functional>
#include<algorithm>
#include<iterator>
using namespace std;
/*
函數擴充卡
一 綁定,用于将二進制函數降為一進制函數
	bindlst()
	template<class Pred,class T>
	binder1st<pred>
	bindlist(const Pred &pr,const T&x)
	Pred是二進制函數
	二進制函數對象第一個參數綁定為x
	傳回值相當于bindr1st<Pred>
	(pr,Pred::first_argument_type(x))

	bind2nd()
	template<class Pred,class T>
	binder2nd<Pred>
	bind2nd(const Pred& pr,const T &y)
	Pred是二進制函數
	二進制函數對象第二個參數綁定為y
	傳回值相當于bindr2nd<Pred>
	(pr,Pred::second_argument_type(y))
二 取反
	not1
	template<class Pred>
	unary _negate<Pred>not1(const pred &pr)
	Pred是一進制函數
	傳回值相當于unary_negate<Pred>(pr)

	not2
	template<class Pred>
	unary _negate<Pred>not2(const pred &pr)
	Pred是二進制函數
	傳回值相當于binary_negate<Pred>(pr)
三 成員函數擴充卡
	men_fun
	template<class R,class T>
	mem_fun_t<R,T>men_fun(R (T::*pm)())
	調用類T中的成員函數

	mem _ fun _ref
	templat<class R,class T>
	mem_fun_ref_t<R,T>
	mem_fun_ref(R(T:: *PM)()) ;
	調用類T中的成員函數
四普通函數擴充卡
	ptr_fun

	把全局函數進一步封裝成一進制函數
    template<class Arg,class Result>
	pointer_to_unary_function<Arg,Result>
	ptr_fun(Result (*pf)(Arg));

    把全局函數進一步封裝成二進制函數
    template<class Arg1,class Arg2,class Result>
	pointer_to_binary_funtion<Arg1,Arg2,Result>
	ptr_fun(Result(*pf)(Arg1,Arg2));
*/
//綁定取反擴充卡基本用法
int main()
{
    int a[]={1,3,5,7,9,8,6,4,2,0};
    /*bind2nd()
	less<int>()是一個二進制函數
    第二個參數綁定為4,bool less(T x,T y){return x<y}
    countif相當于求小于4的個數
     * */
    int nCount=count_if(a,a+sizeof(a)/sizeof(int),bind2nd(less<int>(),4));
    cout<<nCount<<endl;

    /*bind1st()
	less<int>()是一個二進制函數
    第一個參數綁定為4,bool less(T x,T y){return 4<y}
    countif相當于求大于4的個數
     * */
    nCount=count_if(a,a+sizeof(a)/sizeof(int),bind1st(less<int>(),4));
    cout<<nCount<<endl;

    //求大于等于4的個數
    nCount=count_if(a,a+sizeof(a)/sizeof(int),not1(bind2nd(less<int>(),4)));
    cout<<nCount<<endl;
    //求小于等于4的個數
    nCount=count_if(a,a+sizeof(a)/sizeof(int),not1(bind1st(less<int>(),4)));
    cout<<nCount<<endl;
    /*sort()需要傳入二進制函數
     * not2(less<int>())是一個二進制函數,
    相當于bool notless(T x,T y){return x>=y}
    是以元素降序排列
     */
    sort(a,a+sizeof(a)/sizeof(int),not2(less<int>()));

    //每個輸出元素後面加一個附加字元或元素
    copy(a,a+sizeof(a)/sizeof(int),ostream_iterator<int>(cout," "));
}
           

繼續閱讀