1 year ago

#281859

test-img

Henryk

Why does the "[]" operator of std::map<std::string, std::string> accept a double value but gives unexpected output?

We came around the following code snipped:

std::map<std::string, std::string> m;
m["a"] = 42.0;
std::cout << "value=" << m["a"] << std::endl;

Output is:

value=*

It works with all compilers that we tested (via GodBolt). Obviously, the double value 42.0 is implicitly converted to a char (ASCII of 42 is "*"). That was not expected and we find it rather dangerous behaviour.

Why does it work like this? What could we do to avoid such hard-to-find errors?

c++

stl

stdmap

0 Answers

Your Answer

Accepted video resources