示例:
using namespace std;
#include<iostream>
#include<set>
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
class compareperson
{
public:
bool operator()(const Person& p1, const Person& p2)const
{
return p1.m_Age > p2.m_Age;
}
};
//bool compareperson(Person &p1,Person &p2)
//{
// return p1.m_Age > p2.m_Age;
//}
void test01()
{
Person p1("刘备", 26);
Person p2("关羽", 24);
Person p3("张伟", 29);
Person p4("赵云", 18);
Person p5("吕布", 44);
set<Person, compareperson >p;
p.insert(p1);
p.insert(p2);
p.insert(p3);
p.insert(p4);
p.insert(p5);
for (set<Person, bool(*)(string, int)>::iterator it = p.begin(); it != p.end(); it++)
{
cout << "姓名为:" << it->m_Name << " 年龄为:" << it->m_Age << endl;
}
}
int main()
{
test01();
return 0;
}
总结:对于自定义数据类型,set必须指定排序规则才能插入数据