STL中对于函数适配器的小问题 成员函数适配器mem_fun和mem_fun_ref

遥不可及梦 2016-03-05 10:36:49
#include<iostream>
#include<functional>
#include<vector>
#include<algorithm>
#include<string>

using namespace std;

class Student
{
public:
string strNo;
string strName;
public:
Student(string strNo, string strName) : strNo(strNo), strName(strName){}
bool show()
{
cout << strNo << ";" << strName << endl;
return true;
}
};


int main()
{
Student s1("1001", "zhangsan");
Student s2("1002", "lisi");
vector<Student> v;
v.push_back(s1);
v.push_back(s2);
for_each(v.begin(), v.end(), mem_fun_ref(Student::show));

Student *ps1 = new Student("1003", "wangwu");
Student *ps2 = new Student("1004", "zhaoliu");
vector<Student*> pv; //pay an attention
pv.push_back(ps1);
pv.push_back(ps2);
for_each(pv.begin(), pv.end(), mem_fun(Student::show));
return 0;
}
e6_11.cpp: In function ‘int main()’:
e6_11.cpp:38:52: error: invalid use of non-static member function ‘bool Student::show()’
for_each(v.begin(), v.end(), mem_fun_ref(Student::show));
^
e6_11.cpp:45:50: error: invalid use of non-static member function ‘bool Student::show()’
for_each(pv.begin(), pv.end(), mem_fun(Student::show));
^
编译环境ubuntu15.10 g++
不解的是集合基于对象的vector<Student>,用mem_fun_ref
基于对象指针的 vector<Student*> 则用 men_fun
但是出现的编译问题
求各路大神求解不胜感激
...全文
105 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
ri_aje 2016-03-05
  • 打赏
  • 举报
回复
过时的技术了,不要搞了。 用 lambda 就行,或 bind。

64,682

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧