C++基础函数适配器之mem_fun,mem_fun_ref

class person
{
public:
	person(string na, int age)
	{
		name = na;
		nage = age;
	}
	void show()
	{
		cout << name.c_str() << " " << nage << endl;
	}
private:
	string name;
	int nage;
};


void main()
{
	cout << "mem_fun_ref测试\n";
	person p1("tangyong", 22);
	person p2("tangyong", 23);
	person p3("tangyong", 24);
	person p4("tangyong", 25);
	person p5("tangyong", 26);
	vector<person> v{p1,p2,p3,p4,p5 };	
	for_each(v.begin(), v.end(), mem_fun_ref(&person::show));


	cout << "mem_fun测试\n";
	person *ptr1  = new person("tangyong", 22);
	person *ptr2 = new person("tangyong", 23);
	person *ptr3 = new person("tangyong", 24);
	person *ptr4 = new person("tangyong", 25);
	person *ptr5 = new person("tangyong", 26);
	vector<person *> vx{ ptr1, ptr2, ptr3, ptr4, ptr5 };
	for_each(vx.begin(), vx.end(), mem_fun(&person::show));

	for_each(vx.begin(), vx.end(), [](person *ptr){
		delete ptr; });

	system("pause");
}

结果:
C++基础函数适配器之mem_fun,mem_fun_ref_第1张图片
两者区别:
mem_fun_ref的作用和用法跟mem_fun一样,唯一的不同就是:

当容器中存放的是对象实体的时候用mem_fun_ref,

当容器中存放的是对象的指针的时候用mem_fun。

你可能感兴趣的:(C/C++基础,STL,c++,开发语言,后端)