std::map按key排序,需通过vector+sort或multimap实现按value排序:1. 将map转为vector后用自定义比较函数排序;2. 使用multimap插入value-key对利用其自动排序;3. 可封装通用函数提高复用性。

在C++中,std::map 默认是按照 key 进行排序的,底层基于红黑树实现,不直接支持按 value 排序。如果需要按 value 排序,必须通过额外操作实现。以下是具体的实现步骤和方法。
最常用的方式是将 map 中的键值对复制到一个 vector air>
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
std::map<std::string, int> myMap = {
{"apple", 3},
{"banana", 5},
{"orange", 2}
};
// 转为 vector 存储 pair
std::vector<std::pair<std::string, int>> vec(myMap.begin(), myMap.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 << std::endl;
}
return 0;
}
在 std::sort 中传入 lambda 表达式或函数对象来控制排序规则:
可以将原 map 的 value 和 key 互换位置 插入到 multimap
立即学习“C++免费学习笔记(深入)”;
示例代码:
std::multimap<int, std::string> sortedByValue;
for (const auto& p : myMap) {
sortedByValue.insert({p.second, p.first});
}
// 遍历时即为按 value 排序
for (const auto& p : sortedByValue) {
std::cout << p.second << ": " << p.first << std::endl;
}
注意:multimap 允许重复 key,适合 value 有重复的情况。
可封装一个函数,传入 map 返回排序后的 vector 或直接打印:
template<typename K, typename V>
std::vector<std::pair<K, V>> sortByValue(const std::map<K, V>& m) {
std::vector<std::pair<K, V>> vec(m.begin(), m.end());
std::sort(vec.begin(), vec.end(),
[](const auto& a, const auto& b) {
return a.second < b.second;
});
return vec;
}
以上就是C++ map如何按value排序_C++ map自定义排序规则实现步骤的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号