天天看点

绑定取反适配器基本用法.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," "));
}
           

继续阅读