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

标签 c++ sorting stdmap

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

例如,如果插入以下项目:

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

它们将在 map 中按如下顺序排列:

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

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

最佳答案

当默认顺序不适合您时,请使用自定义比较器。
您将其作为第三个模板参数传递(通常默认为 std::less<KeyType>)。
在您的情况下,您可以使用 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 项按键的降序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22591645/

相关文章:

php - Elasticsearch-ICU排序规则关键字字段-挪威语- Elasticsearch 在排序时被视为å

c++ - 将相同的 key (使用 malloc 创建)添加两次以映射

C++:将元素插入 std::map<MyStruct> ,其中 MyStruct 只能聚合初始化并包含 const 唯一指针

c++ - 使用 find 函数时在 std::map 中获取 SIGSEGV

c++ - 索引数组快速排序调试

c# - 在 C# WPF 应用程序中使用 C++11 库有哪些选择?

JavaScript : Dedup 2 dimensional array by single column

algorithm - 如何使用最少的写入次数对数组进行排序?

c++ - 二进制补码表示

C++ - 插入 Vector - 在迭代器之后还是之前?