qfedu-cpp-level/day10/stl_algorithm_demo/f5.cpp

40 lines
1.0 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// mem_fn 有两个重载版本:
// 用法1mem_fn(&MyClass::printMessage) 用于将成员函数转换为函数对象
// 用法2mem_fn(&MyClass::printMessage)(&obj, "hello world") 用于调用成员函数
// mem_fn 是一个函数模板,它接受一个成员函数指针或成员函数引用,并返回一个函数对象,该对象可以调用相应的成员函数。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Stu
{
private:
string name;
int age;
public:
Stu(const string &name, int age) : name(name), age(age) {}
public:
void show()
{
cout << "name is " << name << ", age is " << age << endl;
}
};
int main()
{
vector<Stu> vs;
vs.push_back(Stu("disen", 18));
vs.push_back(Stu("lucy", 20));
vs.push_back(Stu("jack", 15));
vs.push_back(Stu("mack", 19));
// 遍历容器中所有成员,成员函数作为仿函数时,则通过容器成员调用它的仿函数
for_each(vs.begin(), vs.end(), mem_fun_ref(&Stu::show));
return 0;
}