Search code examples
c++data-structuresunordered-map

How to use unordered_map of unordered_maps in c++?


I have below data structures problem ? Could you please help me out. So I my requirement is to initialise this data structures to default values when I add the new data items into this map.

How can I do this efficiently ?

I need a1, a2, a3 should be set to zero for each entry I am going to add.

struct a {
 int a1;
 int a2;
 int a3;
};

struct A {
 struct a A1;
 struct a A2;
};

unordered_map<int, unordered_map<int, struct A>> big_map;

Tried running below code.

    unordered_map<int, struct A> inner_map;
    big_map[0] = inner_map;
    struct A m;
    big_map[0][0] = m;
    cout << "Values: " << big_map[0][0].A1.a1 << ", " << big_map[0][0].A1.a2 << ", " << big_map[0][0].A1.a3 << endl;

Output:

g++ -std=c++11 -o exe b.cc ./exe Values: 0, 0, 1518395376 ./exe Values: 0, 0, -210403408 ./exe Values: 0, 0, -1537331360 ./exe Values: 0, 0, -915603664

So default initialisation is not being done for a3 ?


Solution

  • You can add a default constructor to your structs:

    struct a {
        a() : a1(0), a2(0), a3(0) { }
        ...
    };
    
    struct A {
        A() : A1(), A2() { }
        ...
    };
    

    And then when you add a new struct you can do:

    big_map[5][7] = A();