键为基础数据类型的map、键为结构体的map

基础类型

默认按照键的大小,将键值对从小到大排序

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,即一个键值对数据,要想访问键、值,则使用 点运算符(.)获取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值