众所周知,set/map是自动按从小到大排序的,而且排好序和不可再修改,否则会破坏组织结构
使用要在排序前,指定它的排序规则
①用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 << " ";
}
}
②用仿函数的方式
NULL
插入自定义类型
以set为例
应该就是这样的,但是不知道为什么一直报错
严重性 代码 说明 项目 文件 行 禁止显示状态
错误 C3848 具有类型“const mycompare2”的表达式会丢失一些 const-volatile 限定符以调用“bool mycompare2::operator ()(const person &,const person &)” 20315 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xutility 1481
解决方法 : 在仿函数那块加上const修饰
#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;
}
}