C ++ std :: map项按键降序排列 [英] C++ std::map items in descending order of keys

查看:1095
本文介绍了C ++ std :: map项按键降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用std :: map容器,其键值按降序排列.

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]

它们在地图中的排序方式如下:

They will be ordered in the map like:

position 0: [1, 34]
position 1: [2, 5]
position 2: [3, 67]

我可以反向迭代地图,但是假设下次我插入[-1,60]时.它将放置在第一位置吗?

I can iterate through the map reversely, but suppose the next time I am inserting [-1 , 60]. Will it be placed at the first position?

推荐答案

当默认订单不适合您时,请使用自定义比较器.
您将其作为第三个模板参数(通常默认为std::less<KeyType>)传递.
您可以使用std::greater:

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<KeyType> ).
In your case, you can use std::greater:

std::map<int, int, std::greater<int> > m;

示例代码:

#include <map>
#include <iostream>
#include <functional>

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

结果输出:

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

这篇关于C ++ std :: map项按键降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆