您的位置:首页 > 编程语言 > C语言/C++

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

2014-07-16 04:17 288 查看
在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。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: