C++ std::map items in descending order of keys

前端 未结 2 1560
轻奢々
轻奢々 2020-12-30 23:09

How cal I use std::map container with key value in descending order.

As an example, if insert the following items:

[2 , 5]
[1 , 34]
[3 , 67]
<         


        
2条回答
  •  情歌与酒
    2020-12-30 23:52

    Use a custom comparator when the default order doesn't do it for you.
    You pass it as the third template parameter ( that's normally defaulted to std::less ).
    In your case, you can use std::greater:

    std::map > m;
    

    Example code:

    #include 
    #include 
    #include 
    
    int main() {
      std::map> m { {-1, 77}, {0, 42}, {1, 84} };
      for (const auto& p : m)
        std::cout << '[' << p.first << ',' << p.second << "]\n";
    }
    

    Resulting output:

    [1,84]
    [0,77]
    [-1,42]
    

提交回复
热议问题