请举个例子排序函数对象的成员函数指针:
时间: 2024-02-16 08:00:12 浏览: 63
假设有一个类 Person
,其中有两个成员变量 name
和 age
,我们可以按照年龄从小到大对一组 Person
对象进行排序。下面是一个使用排序函数对象的成员函数指针进行排序的例子:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Person {
public:
string name;
int age;
Person(string n, int a) : name(n), age(a) {}
};
class Compare {
public:
bool operator()(const Person& p1, const Person& p2) const {
return p1.age < p2.age;
}
};
int main() {
vector<Person> people = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 20}};
Compare c;
bool (Compare::*comp)(const Person&, const Person&) const = &Compare::operator();
sort(people.begin(), people.end(), c.*comp);
for (auto& p : people) {
cout << p.name << " " << p.age << endl;
}
return 0;
}
在上面的例子中,我们定义了一个比较函数对象 Compare
,其中 operator()
是比较两个 Person
对象的函数。在 main()
函数中,我们首先创建了一个 Compare
对象 c
,然后定义了一个成员函数指针 comp
,指向 Compare
类的 operator()
函数。最后,我们通过 c.*comp
的方式将成员函数指针传递给 sort
函数,从而实现了按照年龄从小到大对 people
进行排序。
相关推荐


















