从零开始学C++之STL(九):函数适配器bind2nd 、mem_fun_ref 源码分析、函数适配器应用举例...

一、适配器

三种类型的适配器:

容器适配器:用来扩展7种基本容器,利用基本容器扩展形成了栈、队列和优先级队列


迭代器适配器:(反向迭代器、插入迭代器、IO流迭代器)


函数适配器:函数适配器能够将仿函数和另一个仿函数(或某个值、或某个一般函数)结合起来。

针对成员函数的函数适配器

针对一般函数的函数适配器


二、函数适配器示例

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br> 10<br> 11<br> 12<br> 13<br> 14<br> 15<br> 16<br> 17<br> 18<br> 19<br> 20<br> 21<br> 22<br> 23<br> 24<br> 25<br> 26<br> 27<br> 28<br> 29<br> 30<br> 31<br> 32<br></nobr>
#include<iostream>
#include<algorithm>
#include<functional>
#include<vector>

using namespacestd;

boolis_odd( intn)
{
returnn% 2== 1;
}

intmain( void)
{
inta[]={ 1, 2, 3, 4, 5};
vector< int>v(a,a+ 5);

cout<<count_if(v.begin(),v.end(),is_odd)<<endl;

//计算奇数元素的个数
//这里的bind2nd将二元函数对象modulus转换为一元函数对象。
//bind2nd(op,value)(param)相当于op(param,value)
cout<<count_if(v.begin(),v.end(),
bind2nd(modulus< int>(), 2))<<endl;


//bind1st(op,value)(param)相当于op(value,param);
cout<<count_if(v.begin(),v.end(),
bind1st(less< int>(), 4))<<endl;

return 0;
}

这里的bind2nd将二元函数对象modulus转换为一元函数对象。是如何做到的呢?跟踪源码就知道了。

首先,bind2nd 是一个模板函数,如下:

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br></nobr>
//TEMPLATEFUNCTIONbind2nd
template< class_Fn2,
class_Ty> inline
binder2nd<_Fn2>bind2nd( const_Fn2&_Func, const_Ty&_Right)
{
//returnabinder2ndfunctoradapter
typename_Fn2::second_argument_type_Val(_Right);
return(std::binder2nd<_Fn2>(_Func,_Val));
}


将匿名对象modulus<int>() 和 2 传递进去,返回值是std::binder2nd<_Fn2>(_Func,_Val); 即是一个模板类对象,看binder2nd 模板类

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br> 10<br> 11<br> 12<br> 13<br> 14<br> 15<br> 16<br> 17<br> 18<br> 19<br> 20<br> 21<br> 22<br> 23<br> 24<br> 25<br> 26<br> 27<br> 28<br> 29<br> 30<br> 31<br> 32<br> 33<br> 34<br> 35<br> 36<br> 37<br></nobr>

//TEMPLATECLASSbinder2nd
template< class_Fn2>
classbinder2nd
: publicunary_function< typename_Fn2::first_argument_type,
typename_Fn2::result_type>
{
//functoradapter_Func(left,stored)
public:
typedefunary_function< typename_Fn2::first_argument_type,
typename_Fn2::result_type>_Base;
typedef typename_Base::argument_typeargument_type;
typedef typename_Base::result_typeresult_type;

binder2nd( const_Fn2&_Func,
const typename_Fn2::second_argument_type&_Right)
:op(_Func),value(_Right)
{
//constructfromfunctorandrightoperand
}

result_type operator()( constargument_type&_Left) const
{
//applyfunctortooperands
return(op(_Left,value));
}

result_type operator()(argument_type&_Left) const
{
//applyfunctortooperands
return(op(_Left,value));
}

protected:
_Fn2op; //thefunctortoapply
typename_Fn2::second_argument_typevalue; //therightoperand
};

即构造时,binder2nd 的2个成员op 和 value 分别用module<int>() 和 2 初始化。接着看count_if 中的主要代码:


for (; _First != _Last; ++_First)


if (_Pred(*_First))


++_Count;


*_First 就是遍历得到的容器元素了,当满足_Pred 条件时_Count++,此时可以看成是:


std::binder2nd< modulus<int> >(modulus<int>(), 2)(*_First) 也就是调用binder2nd 类的operator() 函数,返回return(op(_Left,value));


也就是modulus<int>()(*_First, 2); 也就是调用modulus 类的operator() 函数,如下:


C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br> 10<br> 11<br> 12<br></nobr>
//TEMPLATESTRUCTmodulus
template< class_Ty>
structmodulus
: publicbinary_function<_Ty,_Ty,_Ty>
{
//functorforoperator%
_Ty operator()( const_Ty&_Left, const_Ty&_Right) const
{
//applyoperator%tooperands
return(_Left%_Right);
}
};

也就是如果左操作数是偶数则返回0,奇数% 2 == 1, 返回为真。最后总结,也就是count_if 计算容器中为奇数的元素个数,简单地


来说,可以理解成这样:bind2nd(op,value)(param)相当于op(param,value); 其中param 是元素值,value是需要绑定的参数,所谓


bind2nd 也即绑定第二个参数的意思,所以才说bind2nd将二元函数对象modulus转换为一元函数对象,因为第二个参数就是2,当然


这里的第一个参数就是遍历得到的容器元素值了。


与bind2nd 类似的还有 bind1st,顾名思义是绑定第一个参数的意思,如下的表达式:


count_if(v.begin(),v.end(),bind1st(less<int>(),4)) ; 也就是说计算容器中大于4的元素个数。这里绑定的是左操作数。


三、函数适配器应用实例


(一)、针对成员函数的函数适配器

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br> 10<br> 11<br> 12<br> 13<br> 14<br> 15<br> 16<br> 17<br> 18<br> 19<br> 20<br> 21<br> 22<br> 23<br> 24<br> 25<br> 26<br> 27<br> 28<br> 29<br> 30<br> 31<br> 32<br> 33<br> 34<br> 35<br> 36<br> 37<br> 38<br> 39<br> 40<br> 41<br> 42<br> 43<br> 44<br> 45<br> 46<br> 47<br> 48<br> 49<br> 50<br></nobr>
#include<iostream>
#include<algorithm>
#include<functional>
#include<vector>
#include<string>

using namespacestd;

classPerson
{
public:
Person( conststring&name):name_(name){}
voidPrint() const
{
cout<<name_<<endl;
}
voidPrintWithPrefix(stringprefix) const
{
cout<<prefix<<name_<<endl;
}
private:
stringname_;
};

voidfoo( constvector<Person>&v)
{
for_each(v.begin(),v.end(),mem_fun_ref(&Person::Print));
for_each(v.begin(),v.end(),bind2nd(mem_fun_ref(&Person::PrintWithPrefix), "person:"));
}

voidfoo2( constvector<Person*>&v)
{
for_each(v.begin(),v.end(),mem_fun(&Person::Print));
for_each(v.begin(),v.end(),bind2nd(mem_fun(&Person::PrintWithPrefix), "person:"));
}

intmain( void)
{
vector<Person>v;
v.push_back(Person( "tom"));
v.push_back(Person( "jerry"));
foo(v);

vector<Person*>v2;
v2.push_back( newPerson( "tom"));
v2.push_back( newPerson( "jerry"));
foo2(v2);
return 0;
}

在foo 函数中,第一行的mem_fun_ref 将空元函数转换为一元函数对象,具体流程大家可以自己跟踪代码,实际上跟上面bind2nd 是类似的,


需要稍微说一下的是传递函数指针的情况:

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br> 10<br> 11<br> 12<br> 13<br> 14<br> 15<br> 16<br> 17<br> 18<br> 19<br> 20<br> 21<br> 22<br> 23<br> 24<br> 25<br> 26<br> 27<br> 28<br> 29<br> 30<br> 31<br> 32<br></nobr>
template< class_Result,
class_Ty> inline
const_mem_fun_ref_t<_Result,_Ty>
mem_fun_ref(_Result(_Ty::*_Pm)() const)
{
//returnaconst_mem_fun_ref_tfunctoradapter
return(std::const_mem_fun_ref_t<_Result,_Ty>(_Pm));
}

//TEMPLATECLASSconst_mem_fun_ref_t
template< class_Result,
class_Ty>
classconst_mem_fun_ref_t
: publicunary_function<_Ty,_Result>
{
//functoradapter(*left.*pfunc)(),const*pfunc
public:
explicitconst_mem_fun_ref_t(_Result(_Ty::*_Pm)() const)
:_Pmemfun(_Pm)
{
//constructfrompointer
}

_Result operator()( const_Ty&_Left) const
{
//callfunction
return((_Left.*_Pmemfun)());
}

private:
_Result(_Ty::*_Pmemfun)() const; //thememberfunctionpointer
};

传入的参数是一个函数指针,也就是void (Person::*_Pm) () const , 传递后 _Pm = &Print,在operator() 函数中


return((_Left.*_Pmemfun)()); _Left 也就是遍历到的Person 类对象,先找到类的函数,然后进行调用。


第二行中mem_fun_ref 接受两个参数,明显是重载的版本,它将一元函数转换为二元函数对象,而bind2nd 再将其转化为一元函数对


象,即绑定了第二个参数为"person: ",跟踪源码可以看见这样的函数调用:

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br></nobr>
_Result operator()(_Ty&_Left,_Arg_Right) const
{
//callfunctionwithoperand
return((_Left.*_Pmemfun)(_Right));
}

也就是将第二个参数当作参数传递给PrintWithPrefix,所以打印出来的带有前缀person:


而mem_fun 就类似了,只不过此次for_each 遍历得到的是对象指针,所以进行函数调用时需要用-> 操作符,如下所示:

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br> 10<br> 11<br></nobr>
_Result operator()( const_Ty*_Pleft) const
{
//callfunction
return((_Pleft->*_Pmemfun)());
}

_Result operator()( const_Ty*_Pleft,_Arg_Right) const
{
//callfunctionwithoperand
return((_Pleft->*_Pmemfun)(_Right));
}

(二)、针对一般函数的函数适配器

例程1:

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br> 10<br> 11<br> 12<br> 13<br> 14<br> 15<br> 16<br> 17<br> 18<br> 19<br> 20<br></nobr>
#include<iostream>
#include<algorithm>
#include<functional>
#include<vector>
#include<string>

using namespacestd;

intmain( void)
{
char*a[]={ "", "BBB", "CCC"};
vector< char*>v(a,a+ 2);
vector< char*>::iteratorit;
it=find_if(v.begin(),v.end(),bind2nd(ptr_fun(strcmp), ""));
if(it!=v.end())
cout<<*it<<endl;

return 0;
}

ptr_fun 将strcmp 二元函数转换为二元函数对象,bind2nd 再将其转化为一元函数对象,即绑定了第二个参数,因为strcmp 是在比较


不相等的情况返回为真,故find_if 查找的是第一个不等于空串的串位置。


例程2:

C++ Code
<nobr>1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br> 10<br> 11<br> 12<br> 13<br> 14<br> 15<br> 16<br> 17<br> 18<br> 19<br> 20<br> 21<br> 22<br> 23<br> 24<br> 25<br></nobr>
#include<iostream>
#include<algorithm>
#include<functional>
#include<vector>
#include<string>

using namespacestd;

boolcheck( intelem)
{
returnelem< 3;
}

intmain( void)
{
inta[]={ 1, 2, 3, 4, 5};
vector< int>v(a,a+ 5);

vector< int>::iteratorit;
it=find_if(v.begin(),v.end(),not1(ptr_fun(check)));
if(it!=v.end())
cout<<*it<<endl;
return 0;
}

ptr_fun 做了一次转换,not1 再转换一次,故find_if 查找的是第一个大于等于3的元素位置。


这些代码的跟踪就留给大家自己完成了,篇幅所限,不能将所有调用过程都显现出来,学习STL还是得靠大家跟踪源码,才能有更深的体会。


参考:

C++ primer 第四版
Effective C++ 3rd
C++编程规范


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值