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
但是出现的编译问题
求各路大神求解不胜感激