初学STL之函数适配器。

所谓函数适配器,也就是将一个仿函数或者另一个仿函数(或者数值)结合成新的仿函数。它声明与

<functional>中,如以下的定义find_if (coll.begin(),coll.end(),bind2nd(greater<int>(),42));

常用的预定义的函数适配器如下:

bindlst(op,value)      //其实它和下面的bind2nd,都是把op是二元仿函数转成一元仿函数,value作为一元仿函数的参数。

bind2nd(op,value)

not1(op)

not2(op)

如以下:

pos=find_if(coll.begin(),coll.end(),not1(bind2nd(modulus<int>,2)));

这其中的bind2nd,就是将容器中的每一元素取模运算。然后要是奇数则应该返回1,1为真,则not1即为假,所以是找coll容器中的第一个偶数值。

 

针对函数成员变量而设的函数适配器。

mem_fun_ref(op)

mem_fun(op)

如以下:

//成员函数适配器
class PersonFunctor
{
private:
	std::string name;
public:
	PersonFunctor(string valueName):name(valueName)
	{
	}
	//成员函数一,打印名称。
	void print() const //定义const类型
	{
		std::cout<<name<<std::endl;
	}
	//成员函数二,带前缀的打印名称。
	void printWithPrefix(std::string prefix) const
	{
		std::cout<<prefix<<name<<std::endl;
	}
};

成员函数适配器定义如下。

//成员函数适配器
void foo(const std::vector<PersonFunctor>& coll)
{
	using std::for_each;
	using std::bind2nd;
	using std::mem_fun_ref;

	//mem_fun_ref只能调用参数等于1个或者无参数的成员变量,因为要是有几个参数,就会产生大量的仿函数。
	for_each(coll.begin(),coll.end(),mem_fun_ref(&PersonFunctor::print));

	//为成员函数传递一个参数
	for_each(coll.begin(),coll.end(),bind2nd(mem_fun_ref(&PersonFunctor::printWithPrefix),"Person:"));
}


调用的验证代码如下:

	cout<<"----------function adapter-------"<<endl;
	vector<PersonFunctor> personVector;
	PersonFunctor person1("Gavin"),person2("Liu"),person3("Gao"),person4("LG"),person5("GL");
	personVector.push_back(person1);
	personVector.push_back(person2);
	personVector.push_back(person3);
	personVector.push_back(person4);
	personVector.push_back(person5);

	foo(personVector);

结果如下:

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值