A map whose key is a basic data type and a map whose key is a structure

basic type

By default, the key-value pairs are sorted from small to large according to the size of the key

map<int,int> mp;

As shown in the figure, a map from int -> int type is defined, and if several key-value pairs are inserted into it, the key-value pairs are based on the size of the key,From small to largeto be sorted.
example

#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;
}

operation result:

1 -> 1
9 -> 1
100 -> 1

Sort key-value pairs from largest to smallest according to the size of the key

If you want to sort from large to small according to the size of the key, how to establish? Because the bottom layer of the map is implemented using a red-black tree, which is similar to a set, you can add sorting rules like the 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;
}

operation result

100 -> 1
9 -> 1
1 -> 1

It can be seen that the key-value pairs in the map are sorted from large to small according to the size of the key.

Custom structs as keys

If you use a self-defined structure as a key, you must customize the collation of the structure. Or because the bottom layer of the map is implemented using a red-black tree, so its sorting rules are the same as sort and set, and opposite to 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;
}

operation result

(100 200)->1
(100 1)->1
(1 200)->1

It can be seen that the key-value pairs are sorted according to the rules written in the structure.
Note that using auto cur: mp, the obtained cur is a pair, that is, a key-value pair data. If you want to access the key and value, use the dot operator (.) to get it.

Guess you like

Origin blog.csdn.net/weixin_44321570/article/details/123429361