我如何使用具有降序键值的 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/