对于std::map,默认使用std::less作为比较函数,我们可以通过自定义比较函数,来实现其他排序的std::map。

以下是示例代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include  <iostream>
#include  <map>
#include  <unordered_map>
#include  <vector>

class CLessCmp
{
public:
    bool operator()(int x,int y)
    {
        return x < y;
    }
};

class CGreatCmp
{
public:
    bool operator() (int x,int y)
    {
        return x > y;
    }
};

int main(int argc,char * argv[])
{

    std::map<int,int> defaultMap;

    std::map<int,int,CLessCmp> lessMap;

    std::map<int,int,CGreatCmp> greatMap;

    std::vector<int> orgVector={1,4,2,3,8,9,6};


    for(const auto & item:orgVector)
    {
        lessMap.insert(std::pair<int,int>(item,item));
        greatMap.insert(std::pair<int,int>(item,item));
        defaultMap.insert(std::pair<int,int>(item,item));
    }

    std::cout << "Default Map  " << std::endl;
    for(const auto& item:defaultMap)
    {
        std::cout<<item.first<<"\t";
    }
    std::cout<<std::endl;


    //lessMap
    std::cout << "Less Map   "  <<std::endl;
    for(const auto& item:lessMap)
    {
        std::cout << item.first << "\t";
    }
    std::cout<<  std::endl;
    std::cout << "great Map  " << std::endl;
    for(const auto& item:greatMap)
    {
        std::cout << item.first << "\t";
    }
    std::cout<<std::endl;

    return 0;
}

程序的输出如下:

可以看出: 默认的std::map的对于key的排序是从小到大。 自定义排序算法以后,输出改为从大到小。