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

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


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

 

实例代码如下所示:

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

using namespace std;


void findEmptyString(const vector<string>& 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~"<<endl;
	}else
	{
		cout<<"empty string at position: "<<it - strings.begin()<<endl;
	}
}

int main()
{
	vector<string> 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;
}
运行效果如下图


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

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

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


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值