set自定义数据类型指定排序规则

#include <iostream>
#include <set>
#include <algorithm>
using namespace std;

class Person
{
public:
   Person(string name, int age):
   name(name),
   age(age)
   {}

   string name;
   int age;
};

class Print
{
public:
   void operator()(Person p)
   {
      cout << p.name << " " << p.age << endl;
   }
};

class Compare
{
public:
   bool operator()(Person p1, Person p2)
   {
      return p1.age > p2.age;
   }
};

int main()
{
   Person p1("furong", 10);
   Person p2("quange", 8);
   Person p3("zhangsan", 20);

   set<Person, Compare> s;
   s.insert(p1);
   s.insert(p2);
   s.insert(p3);

   for_each(s.begin(), s.end(), Print());

   return 0;
}
$ ./a.out          
zhangsan 20
furong 10
quange 8
posted @ 2022-07-29 00:01  thomas_blog  阅读(89)  评论(0编辑  收藏  举报