c ++ std映射键,按降序排列 [英] c++std map key with descending order

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

问题描述

如何以递减顺序使用带有键值的stl地图容器。

How to use stl map container with key value in descending order.

例如,如果我要插入:

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

它将在地图中:

position 0: [ 3 , 67 ];
position 1 : [ 2 , 5 ]
etc..

反向迭代地图,但我的要求是像上面。
假设下次插入[-1,60]它将在最后一个位置。

I can iterate through map reversely, but my requirement is like above. Suppose next time I am inserting [-1 , 60] it will be at last 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>

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映射键,按降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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