C++标准库---成员函数配接器

针对成员函数而设计的函数配接器

C++标准库提供了一些额外的函数配接器,通过他们,就可以对群集内的每一个元素调用其成员函数。


配接器:

mem_fun_ref(op)  调用op,那是某对象的一个const成员函数

mem_fun(op)  调用op,那是某对象指针的一个const成员函数


代码示例:

#include<iostream>
#include<functional>
#include<algorithm>
#include<vector>
#include<string>

using namespace std;

class Person
{
private:
	string name;
public:
	Person(string n):name(n){}

	void print() const
	{
		cout<<name<<endl;
	}
	void printWithPrefix(string prefix) const
	{
		cout<<prefix<<name<<endl;
	}
};

int main()
{
	Person person1="lanzhihui";
	Person person2="wangdan";
	Person person3="lan";
	Person person4="wang";

	vector<Person> coll;

	coll.push_back(person1);
	coll.push_back(person2);
	coll.push_back(person3);
	coll.push_back(person4);

	for_each(coll.begin(),coll.end(),mem_fun_ref(&Person::print));//单纯调用成员函数

	for_each(coll.begin(),coll.end(),bind2nd(mem_fun_ref(&Person::printWithPrefix),"person:"));//使用bind2nd可以向被调用的成员函数传递一个参数

	system("pause");
	return 0;
}

运行结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值