1.set存放自定义数据类型,set必须指定排序规则才可以插入数据
#include<iostream>
#include<set>
using namespace std;
class person
{
public:
person(string name,int age)
{
this->myname = name;
this->myage = age;
}
string myname;
int myage;
};
class compareperson
{
public:
bool operator()(const person & p1, const person & p2) const
{
return p1.myage > p2.myage;
}
};
void test1()
{
//自定义数据类型,都会指定排序
set<person , compareperson> s;
person p1("刘备", 24);
person p2("关羽", 28);
person p3("张飞", 25);
person p4("赵云", 24);
s.insert(p1);
s.insert(p2);
s.insert(p3);
s.insert(p4);
for (set<person , compareperson>::iterator i = s.begin(); i != s.end(); i++)
{
cout << "姓名: " <<i->myname<< " 年龄: "<<(*i).myage<<endl;
}
/*打印结果:
姓名: 关羽 年龄: 28
姓名: 张飞 年龄: 25
姓名: 刘备 年龄: 24
*/
}
int main()
{
test1();
system("pause");
return 0;
}