c++11调用成员函数mem_fn和适合普通函数指针

在C++11之前,调用一个成员函数指针做为容器的回调算法时,可以根据其容器内存储的内容是对象还是指针调用相关的mem_fun和_mem_fun_ref函数来与算法等进行适配,搭配使用。


在c++11中加入mem_fn来对成员函数的调用进行相关的封装,不过也需要对方法指针定义为成员函数的形式。

 

实例代码如下所示:

#include 
#include 
#include 
#include 
#include 

using namespace std;


void findEmptyString(const vector& strings)
{
	auto end = strings.end();
	auto it = find_if(strings.begin(), end, mem_fn(&string::empty) );  //此处的成员函数指针要表示为相应的成员函数的形式,且使用mem_fn进行包装

	if ( it == end)
	{
		cout<<"no empty strings~"< myVector;
	string one = "buaa";
	string two = "";
	myVector.push_back(one);
	myVector.push_back(one);
	myVector.push_back(two);
	myVector.push_back(one);

	findEmptyString(myVector);

	system("pause");
	return 0;
}
运行效果如下图

c++11调用成员函数mem_fn和适合普通函数指针_第1张图片


当然,这里最好的,最为优雅的方式还是转用lambda的方式进行实现。如下代码所示:

	auto it = find_if(strings.begin(), end,
		[](const string* str){ return str->empty(); });

实现相同的功能,爱死你了auto。。


你可能感兴趣的:(C/C++,c++11mem_fn,mem_fn和lambda,mem_fn)