针对成员函数而设计的函数配接器
C++标准库提供了一些额外的函数配接器,通过他们,就可以对群集内的每一个元素调用其成员函数。
配接器:
mem_fun_ref(op) 调用op,那是某对象的一个const成员函数
mem_fun(op) 调用op,那是某对象指针的一个const成员函数
代码示例:
#include<iostream>
#include<functional>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
class Person
{
private:
string name;
public:
Person(string n):name(n){}
void print() const
{
cout<<name<<endl;
}
void printWithPrefix(string prefix) const
{
cout<<prefix<<name<<endl;
}
};
int main()
{
Person person1="lanzhihui";
Person person2="wangdan";
Person person3="lan";
Person person4="wang";
vector<Person> coll;
coll.push_back(person1);
coll.push_back(person2);
coll.push_back(person3);
coll.push_back(person4);
for_each(coll.begin(),coll.end(),mem_fun_ref(&Person::print));//单纯调用成员函数
for_each(coll.begin(),coll.end(),bind2nd(mem_fun_ref(&Person::printWithPrefix),"person:"));//使用bind2nd可以向被调用的成员函数传递一个参数
system("pause");
return 0;
}
运行结果: