Accessing a std::map of std::map like an array

醉酒当歌 提交于 2021-02-11 16:55:08

问题


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"];

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.


回答1:


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}},

Should become

 {"mHz",    {{"mHz",     1.0},
            {"Hz",      1e-3}}},


来源:https://stackoverflow.com/questions/23214788/accessing-a-stdmap-of-stdmap-like-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!