C++ std::map 项按键降序排列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22591645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:08:14  来源:igfitidea点击:

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

c++sortingstdmap

提问by Sigcont

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

我如何以降序使用带有键值的 std::map 容器。

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]

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?

我可以反向遍历地图,但假设下次我插入 [-1 , 60]。会放在第一位吗?

回答by jrok

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::less<KeyType>)。
在您的情况下,您可以使用std::greater

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

Example code:

示例代码:

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

Resulting output:

结果输出:

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

回答by user3447428

std::mapis already sorted, so you only need to traverse the map using a reverse_iterator.

std::map已经排序,因此您只需要使用reverse_iterator.

A map, however, is not an array. There's no such thing as "the n-th position" in a map. (std::mapis most commonly implemented using some sort of binary search tree.) If you absolutely, inevitablyneed to specify order manually, then use a std::vector<std::pair>.

然而,地图不是数组。地图中没有“第 n 个位置”这样的东西。(std::map最常使用某种二叉搜索树来实现。)如果您绝对不可避免地需要手动指定顺序,那么使用std::vector<std::pair>.