std::map 不能直接按 value 排序因其排序基于 key,需用 vector 或 multimap 辅助实现。

在C++中,std::map 默认是按照 key 进行升序排序的,且其内部结构(通常是红黑树)决定了它不能直接按 value 排序。但我们可以借助其他容器和算法来实现按 value 排序的需求。
std::map 的设计初衷是基于 key 快速查找,它的排序规则绑定在 key 上。一旦插入键值对,就会根据 key 自动排序,无法更改排序依据。因此要按 value 排序,必须将数据导出到支持自定义排序的容器中,比如 vector 或 list。
将 map 中的所有元素复制到一个 vector
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
std::map<std::string, int> m = {
{"apple", 3},
{"banana", 1},
{"cherry", 4},
{"date", 2}
};
// 将 map 转为 vector<pair>
std::vector<std::pair<std::string, int>> vec(m.begin(), m.end());
// 按 value 升序排序
std::sort(vec.begin(), vec.end(),
[](const auto& a, const auto& b) {
return a.second < b.second;
});
// 输出结果
for (const auto& p : vec) {
std::cout << p.first << ": " << p.second << "\n";
}
return 0;
}
输出:
banana: 1 date: 2 apple: 3 cherry: 4
可以封装排序逻辑,支持升序、降序或更复杂的规则。
按 value 降序:
std::sort(vec.begin(), vec.end(),
[](const auto& a, const auto& b) {
return a.second > b.second;
});
若 value 相同,按 key 字典序排序:
std::sort(vec.begin(), vec.end(),
[](const auto& a, const auto& b) {
if (a.second == b.second)
return a.first < b.first;
return a.second < b.second;
});
利用 multimap 允许重复 key 的特性,把原 map 的 value 作为新 multimap 的 key,实现自动排序。
示例:
std::multimap<int, std::string> sorted_by_value;
for (const auto& pair : m) {
sorted_by_value.insert({pair.second, pair.first});
}
// 遍历时已按 value 升序
for (const auto& pair : sorted_by_value) {
std::cout << pair.second << ": " << pair.first << "\n";
}
按 value 排序 map 并不复杂,关键是选择合适的方法:
基本上就这些。记住:map 本身不可变排序方式,但结合 STL 算法能轻松实现需求。
以上就是c++++中如何对map按value排序_map自定义排序与值排序方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号