Insert a value to a map of map when none of the map is initialized

4026 views c++
0

I've seen a code that does the following behavior:

std::map<std::string, std::map<std::string, std::string>> obj;

obj["123"]["456"] = "789";

How does it make sense? The first map (obj["123"]) was not needed to be initialized first? such as:

std::map<std::string, std::map<std::string, std::string>> obj;
obj["123"] = std::map<std::string,std::string>();
obj["123"]["456"] = "789";

Thanks a lot!

answered question

1 Answer

7

When using [] to "index" a map, if the key isn't found then an entry will be created and inserted into the map for that key.

So for your example:

obj["123"]["456"] = "789";

that is essentially equal to

// Create an element for the key "123"
obj.insert(std::pair<std::string, std::map<std::string, std::string>>("123", std::map<std::string, std::string>());

// Create an element for the key "456" in the map obj["123"]
obj["123"].insert(std::pair<std::string, std::string>("456", "789");

posted this

Have an answer?

JD

Please login first before posting an answer.