- map和set都是按照从小到大的顺序进行排序的,且排序好后不能轻易更改,否则会破坏组织结构;
如何让其在插入过程中可以自动的变成由大到小的排序方式呢?
tips:set在进行插入的时候一般会按照**<来比较关键字,所以其插入好的状态一般是从小到大;
但是对于自定义类型,就需要重载<来支持这一操作;
1、使用set前指定比较方式为greater**
void test()
{
set<int,greater<int>>S2;
S2.insert(10);
S2.insert(100);
S2.insert(200);
for (set<int>::iterator it = S2.begin(); it != S2.end(); it++)
{
cout << *it << " ";
}
}
2、利用仿函数(对于自定义类型,重载小括号)
#include <iostream>
#include<cstdlib>
#include<string>
#include<set>
using namespace std;
class person
{
public:
person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
class mycompare2
{
public:
bool operator()(const person& p1, const person& p2)const
// 这个位置要加const修饰
{
if (p1.m_age > p2.m_age) //降序
{
return true;
}
return false;
}
};
void test4()
{
set<person, mycompare2> p;
person p1("sss", 35);
person p2("aaa", 10);
person p3("bbb", 20);
person p4("ccc", 46);
person p5("ddd", 82);
p.insert(p1);
p.insert(p2);
p.insert(p3);
p.insert(p4);
p.insert(p5);
//插入自定义数据类型 需要指定排序规则
//显示
for (set<person, mycompare2>::iterator it = p.begin(); it != p.end(); it++)
{
cout << "姓名: " << (*it).m_name << "年龄: " << it->m_age << endl;
}
}
注:资料来源于网络,侵权删