关于map的排序规则:
- std::map 默认按照键(第一个字段)从小到大排序,使用
std::less<Key>
作为比较函数 - map中每个键必须是唯一的,因此默认情况下第二个字段(值)不参与排序
如果您想使用自定义的排序规则,可以提供自己的比较函数:
#include <map>
#include <iostream>
#include <functional> // 包含greater, lower
int main() {
// 使用降序即从大到小排列的map
std::map<int, std::string, std::greater<int>> myMap = {
{1, "一"}, {2, "二"}, {3, "三"}
};
for (const auto& [key, value] : myMap) {
std::cout << key << ": " << value << std::endl;
}
// 输出:3: 三 2: 二 1: 一
return 0;
}