【问题标题】:Insert a value to a map of map when none of the map is initialized [duplicate]当没有初始化地图时,将值插入地图的地图[重复]
【发布时间】:2019-04-07 21:54:43
【问题描述】:

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

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

非常感谢!

【问题讨论】:

    标签: c++ dictionary


    【解决方案1】:

    当使用[] 来“索引”一个映射时,如果没有找到该键,则将创建一个条目并将其插入到该键的映射中。

    所以对于你的例子:

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

    【讨论】:

    • 很好的解释。谢谢程序员老兄!
    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    相关资源
    最近更新 更多