像数组一样访问std :: map的std :: map [英] Accessing a std::map of std::map like an array
问题描述
我已经初始化了std :: map的std :: map,如下所示:
I have initialize a std::map of a std::map like as below:
static std::map<std::string, std::map<std::string, float>> _ScalingMapFrequency = {
{"mHz", {{"mHz", 1.0}}},
{"mHz", {{"Hz", 1e-3}}},
{"Hz", {{"mHz", 1e+3}}},
{"Hz", {{"Hz", 1.0}}}};
现在我正尝试通过以下方式访问浮点值:
And now I am trying to access the float values in the following way:
std::cout<<" the scaling factor is :"<<_ScalingMapFrequency["mHz"]["Hz"];
编译和运行代码没有问题,但是我希望得到"1e-3",而我总是得到"0".我需要以数组形式访问std :: map"_ScalingMapFrequency",这是设计决策.
There is no problem when I compile and run the code but I am expecting to get "1e-3" instead I am always getting a "0". I need to access the std::map "_ScalingMapFrequency" as an array, that being the design decision.
我犯了什么错误?请给我一些指导,我将不胜感激.
What mistake I am making ? Please give me some pointer and I would greatly appreciate.
推荐答案
地图不能有重复的键,因此当您执行 {"mHz",{{"Hz",1e-3}}},
,它覆盖了第一个,而不是合并它们.
A map cannot have duplicate keys, thus when you do {"mHz", {{"Hz", 1e-3}}},
for the second time, it overwrites the first one, as opposed to merge them.
您应该更改构造函数,以便将它们合并为开始.
You should change the constructor so that they are merged to begin with.
{"mHz", {{"mHz", 1.0}},
{"mHz", {{"Hz", 1e-3}},
应该成为
{"mHz", {{"mHz", 1.0},
{"Hz", 1e-3}}},
这篇关于像数组一样访问std :: map的std :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!