#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
/*
自定义仿函数
*/
class Person {
public:
Person(int age = 0, string name = "") :age(age), name(name) {};
int getAge() {
return this->age;
}
string getName() {
return this->name;
}
//相当于JAVA重载toString方法
friend ostream& operator << (ostream& os, Person p) {
os << "age = " << p.age << " name = " << p.name << endl;
return os;
}
private:
int age;
string name;
};
//public unary_function<Person, bool>可以不加 加了只是为了融入STL(参考侯捷STL源码剖析)
//以下为自定义仿函数 其实就是重载了()
struct cmpPerson : public unary_function<Person, bool> {
bool operator()(Person p1, Person p2) {
if (p1.getAge() != p2.getAge()) {
return p1.getAge() > p2.getAge();
}
else {
return p1.getName() > p2.getName();
}
}
};
int main()
{
//仿函数在set/map里运用 直接放入模板参数
set<Person, cmpPerson >personSet;
personSet.insert(Person(2, "tj"));
personSet.insert(Person(2, "jj"));
personSet.insert(Person(3, "tj"));
personSet.insert(Person(4, "aj"));
for (auto it = personSet.begin(); it != personSet.end(); it++) {
cout << *it;
}
//仿函数在vector的sort中运用
vector<Person>personVector;
personVector.push_back(Person(2, "tj"));
personVector.push_back(Person(2, "jj"));
personVector.push_back(Person(3, "tj"));
personVector.push_back(Person(4, "tj"));
//cmpPerson为类名 sort里需要放入一个类对象 cmpPerson()表示一个临时对象
sort(personVector.begin(), personVector.end(), cmpPerson());
for (auto it = personVector.begin(); it != personVector.end(); it++) {
cout << *it;
}
return 0;
}
set/map/vector中自定义仿函数
最新推荐文章于 2023-06-13 23:48:45 发布