user997112
user997112

Reputation: 30655

Inserting in to an unordered_map of unordered_map?

I have a data structure which is an unordered_map of 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. 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).

What is the cleanest way to do this?

Upvotes: 3

Views: 8499

Answers (1)

Nikolay K
Nikolay K

Reputation: 3850

If you don't use pointers you could simply use operator[] on both maps.

#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

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

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

Upvotes: 6

Related Questions