std::map默认按key升序排列,可通过自定义比较器实现key降序;按value排序需将元素复制到vector等容器后使用std::sort。示例展示了key升序、key降序及value升序、降序的实现方法,其中value排序需额外处理。

在C++中,std::map 默认是按照 key 自动排序的,且默认为升序。这种排序是在插入元素时自动完成的,底层通常由红黑树实现。但有时我们需要根据 value 进行排序,这就需要额外操作。下面分别介绍按 key 排序和按 value 排序的方法。
1. std::map 按 key 排序(默认行为)
std::map 本身就以 key 为索引进行有序存储,默认按 key 升序排列。不需要额外操作。
示例代码:
#include <iostream>
#include <map>
using namespace std;
<p>int main() {
map<string, int> m = {{"banana", 3}, {"apple", 5}, {"cherry", 2}};</p><pre class='brush:php;toolbar:false;'>// 自动按 key 升序输出
for (const auto& pair : m) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
输出结果:
立即学习“C++免费学习笔记(深入)”;
apple: 5
banana: 3
cherry: 2
key 已按字典序自动排序。
2. 自定义 key 排序方式(如降序)
可以通过自定义比较函数对象或 lambda 表达式来改变排序规则。例如,让 map 按 key 降序排列。
示例:按 key 降序
#include <iostream>
#include <map>
using namespace std;
<p>int main() {
map<string, int, greater<string>> m = {{"banana", 3}, {"apple", 5}, {"cherry", 2}};</p><pre class='brush:php;toolbar:false;'>for (const auto& pair : m) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
输出结果:
立即学习“C++免费学习笔记(深入)”;
cherry: 2
banana: 3
apple: 5
3. 按 value 排序
std::map 不支持直接按 value 排序。要实现这一点,需将 map 中的元素复制到一个容器(如 vector)中,然后使用 std::sort 自定义比较规则。
示例:按 value 升序排序
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
<p>int main() {
map<string, int> m = {{"banana", 3}, {"apple", 5}, {"cherry", 2}};</p><pre class='brush:php;toolbar:false;'>// 将 map 转为 vector<pair>
vector<pair<string, int>> vec(m.begin(), m.end());
// 按 value 升序排序
sort(vec.begin(), vec.end(), [](const auto& a, const auto& b) {
return a.second < b.second;
});
// 输出结果
for (const auto& pair : vec) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
输出结果:
立即学习“C++免费学习笔记(深入)”;
cherry: 2
banana: 3
apple: 5
若要按 value 降序:
把比较条件改为 a.second > b.second 即可。
4. 注意事项
- map 的排序只针对 key,且在插入时即时维护有序性。
- 若要频繁按 value 查询或排序,考虑是否更适合用 vector 存储 pair 并手动排序。
- 若 value 相同,按 value 排序时不会保持 key 的有序性,除非在比较函数中添加第二关键字。
基本上就这些。map 按 key 排序是内置功能,按 value 排序则需借助外部容器和算法。不复杂但容易忽略细节。










