简体   繁体   English

插入unordered_map的unordered_map?

[英]Inserting in to an unordered_map of unordered_map?

I have a data structure which is an unordered_map of unordered_map: 我有一个数据结构,它是unordered_map的unordered_map:

typedef std::unordered_map<string, int> map1;
typedef std::unordered_map<string, map1> map2;

and I would like to insert an element in to map1, without needing to use IF statements to check whether it already exists. 我想在map1中插入一个元素,而不需要使用IF语句来检查它是否已经存在。 However, I am a bit confused because map2 doesn't have a value unless you already have the map1 element, but the map1 element comes from map2 (if it already exists there). 但是,我有点困惑,因为map2没有值,除非你已经有map1元素,但map1元素来自map2(如果它已经存在)。

What is the cleanest way to do this? 最干净的方法是什么?

If you don't use pointers you could simply use operator[] on both maps. 如果你不使用指针,你可以在两个地图上使用operator[]

#include <iostream>
#include <unordered_map>
#include <string>

typedef std::unordered_map<std::string, int> map1;
typedef std::unordered_map<std::string, map1> map2;

int main()
{
    map2 m2;
    m2["a"]["b"] = 1;

    std::cout << m2["a"]["b"] << std::endl;
}

If there is the case with only map2* you could do as follows 如果只有map2*的情况,你可以这样做

int main()
{
    map2* m1 = new map2();
    map2& m2 = *m1;
    m2["a"]["b"] = 1;

    std::cout << m2["a"]["b"] << std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM