0

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 Answer 1

4

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}}},
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much for the reply. I missed that basic thingy. What I need is to have the mapping of {"mHz", {{"Hz", 1e-3}}} and {"mHz", {{"mHz", 1e-3}}}... How could I achieve this without mentioning "mHz" for the second time...I mean how do I correctly initialize without repetition of the key ?
Ohh awesome...Let me try that. Thank you so very much for your quick reply !!
If the brackets are confusing, I suggest initializing it in 2 steps, first the inner map, and then use it to init the outer map
Thank you so much !! It worked like a charm...:) :) I dont know how could I missed that basic stuffs ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.