在未初始化映射的情况下,将值插入到映射的映射中

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

本文关键字:映射 插入 情况下 初始化      更新时间:2023-10-16

我看到了一个执行以下行为的代码:

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

这有什么意义?第一个映射(obj["123"](不需要先初始化吗?例如:

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

非常感谢!

使用[]对映射进行"索引"时,如果找不到键,则会创建一个条目并将其插入该键的映射中。

举个例子:

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

基本上等于

// Create an element for the key "123", and store a std::map<std::string, std::string> object for that key
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"));