#include<iostream>
#include<deque>
#include<vector>
#include<stack>
#include<algorithm>
#include<Queue>
#include<ctime>
#include<list>
#include<set>
using namespace std;
//set容器排序
class MyCompare
{
public:
bool operator()(int a,int b) const
{
return a > b;
}
};
void test01()
{
set<int>s1;
s1.insert(10);
s1.insert(30);
s1.insert(20);
s1.insert(40);
for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//指定排序规则 从大到小
set<int,MyCompare>s2;
s2.insert(10);
s2.insert(30);
s2.insert(20);
s2.insert(40);
for (set<int, MyCompare>::iterator it = s2.begin(); it != s2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void test02()
{
}
int main()
{
test01();
//test02();
system("pause");
return 0;
}
自定义类型数据排序
#include<iostream>
#include<deque>
#include<vector>
#include<stack>
#include<algorithm>
#include<Queue>
#include<ctime>
#include<list>
#include<set>
using namespace std;
//set容器排序
//自定义的数据类型 都会指定排序规则
class Person
{
public:
Person(string name, int age)
{
this->m_Age = age;
this->m_Name = name;
}
string m_Name;
int m_Age;
};
class MyCompare
{
public:
bool operator()(const Person &p1, const Person &p2) const
{
//按照年龄降序
return p1.m_Age > p2.m_Age;
}
};
void test01()
{
set<Person, MyCompare>s;
Person p1("A", 28);
Person p2("D", 38);
Person p3("H", 19);
Person p4("C", 24);
s.insert(p1);
s.insert(p2);
s.insert(p3);
s.insert(p4);
for (set<Person, MyCompare>::iterator it = s.begin(); it != s.end(); it++)
{
cout << "姓名:" << (*it).m_Name << " 年龄:" << (*it).m_Age << endl;
}
}
void test02()
{
}
int main()
{
test01();
//test02();
system("pause");
return 0;
}