【发布时间】:2018-08-28 10:15:48
【问题描述】:
我试图弄清楚如何按值的升序对std::map 进行排序。
我的代码:
#include <iostream>
#include <map>
#include <string>
#include <iterator>
void printMapByOrder(std::map<std::string, int> mapOfPlanets)
{
//what should be here?
}
int main() {
std::map<std::string, int> mapOfPlanets;
mapOfPlanets["earth"] = 12;
mapOfPlanets["jupiter"] = 142;
mapOfPlanets["mars"] = 6;
mapOfPlanets["mercury"] = 4;
mapOfPlanets["neptune"] = 49;
mapOfPlanets["pluto"] = 2;
mapOfPlanets["saturn"] = 120;
mapOfPlanets["uranus"] = 51;
mapOfPlanets["venus"] = 12;
printMapByOrder(mapOfPlanets);
}
我想要的结果:
pluto : 2
mercury : 4
mars : 6
earth : 12
venus : 12
neptune : 49
uranus : 51
saturn : 120
jupiter : 142
std::map 可以做到这一点吗?
【问题讨论】:
-
您是要按升序对地图进行排序(您的文字内容和欺骗的内容)还是要对地图进行降序排序并仅按升序打印其元素(您的代码建议)
-
建议的欺骗是错误的。这个问题是关于排序值而不是键。
-
@ZackLee 听起来您正在寻找类似的东西,boost.org/doc/libs/1_68_0/libs/multi_index/doc/index.html
-
用
std::sort和谓词对向量进行排序是性能更好的解决方案。我们在谈论多少个条目?十几个人,你做什么都没关系。先进行基准测试,然后再考虑性能。 -
所以这是几千字节的 RAM。我会从更容易编码和理解的东西开始,然后从那里开始工作。基准测试会告诉您什么是足够快的。