std::map默认按键排序,若需按值排序可将元素复制到vector中使用std::sort配合自定义比较函数实现,支持升序、降序及复杂比较逻辑,但会带来复制开销。

在C++中,std::map 默认是根据键(key)进行排序的,且不支持直接按值(value)排序。如果需要按 value 排序,可以通过将 map 中的元素复制到一个支持自定义排序的容器(如 vector 或 set)中来实现。
将 map 中的每个键值对拷贝到 vector 中,然后使用 std::sort 自定义比较函数,按 value 排序。
示例代码:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
std::map<std::string, int> m = {
{"apple", 3},
{"banana", 1},
{"orange", 4},
{"grape", 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;
}
输出:
立即学习“C++免费学习笔记(深入)”;
banana: 1只需修改比较函数即可实现降序:
std::sort(vec.begin(), vec.end(),
[](const auto& a, const auto& b) {
return a.second > b.second; // 降序
}
);
方法相同,只需调整比较逻辑。例如按字符串长度排序:
std::map<int, std::string> m = {{1,"hi"}, {2,"hello"}, {3,"a"}};
std::vector<std::pair<int, std::string>> vec(m.begin(), m.end());
std::sort(vec.begin(), vec.end(),
[](const auto& a, const auto& b) {
return a.second.length() < b.second.length();
}
);
以上就是c++++中如何对map按值(value)进行排序_c++ map根据value排序的实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号