基础类型
默认按照键的大小,将键值对从小到大排序
map<int,int> mp;
如图所示,定义了一个从int -> int类型的map,并且,如果往里面插入几个键值对,键值对是按照键的大小,从小到大进行排序的。
示例
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<int,int> mp;
mp[9] = 1;
mp[100] = 1;
mp[1] = 1;
for (auto it = mp.begin(); it != mp.end(); it++) {
printf("%d -> %d\n",it->first, it->second);
}
return 0;
}
运行结果:
1 -> 1
9 -> 1
100 -> 1
按照键的大小,从大到小排序键值对
如果想要按照键的大小,从大到小进行排序,如果建立?因为map底层是使用红黑树实现的,类似于set,所以,可以向set一样,添加排序规则。
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<int,int,greater<int> > mp; // 不同之处,有第三个参数
mp[9] = 1;
mp[100] = 1;
mp[1] = 1;
for (auto it = mp.begin(); it != mp.end(); it++) {
printf("%d -> %d\n",it->first, it->second);
}
return 0;
}
运行结果
100 -> 1
9 -> 1
1 -> 1
可以看到,这次map里面的键值对,是按照键的大小,从大到小进行排序的。
自定义的结构体作为键
如果使用自己定义的结构体作为键,必须自定义结构体的排序规则。还是因为map底层是使用红黑树实现的,所以,其排序规则和sort、set一样,和priority_queue相反。
#include <bits/stdc++.h>
using namespace std;
struct node {
int x, y;
node () {
}
node (int _x, int _y) : x(_x), y(_y) {
}
bool operator < (const node &b) const {
if (x != b.x) return x > b.x; // x大的在前
else return y > b.y; // x相同时,y大的在前
}
};
map<node,int> mp;
int main()
{
mp[node(100,1)] = 1;
mp[node(1,200)] = 1;
mp[node(100,200)] = 1;
for (auto cur : mp) {
printf("(%d %d)->%d\n",cur.first.x,cur.first.y,cur.second);
}
return 0;
}
运行结果
(100 200)->1
(100 1)->1
(1 200)->1
可以看到,是按照在结构体里面写的规则进行的键值对的排序。
注意,其中使用 auto cur:mp,得到的 cur 是一个pair,即一个键值对数据,要想访问键、值,则使用 点运算符(.)获取。