3

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 ?

2
  • 3
    @SombreroChicken No need for that, after c++11 inserting to a map leads to a default initialisation, even if the type does not have a constructor e.g. ints, floats etc. Commented Jun 1, 2018 at 16:02
  • 1
    @KostasRim That was the generalized answer, not including C++11. But then again unordered_map is C++11 only so you're right. Commented Jun 1, 2018 at 16:06

3 Answers 3

6

Since C++11 you can do this:

struct a {
 int a1 = 0;
 int a2 = 0;
 int a3 = 0;
};
Sign up to request clarification or add additional context in comments.

Comments

2

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

6 Comments

I did not understand why A1() ?, A1 is variable
@jpb123 A1 is a struct object. A1() in the initialization list is explicitly calling its default constructor to set a1, a2, a3 to 0.
@jpb123 Do you mean in the initialiser-list of A's constructor? It default initialises the A1 member variable.
@scohe001, Thank you so much. I was not knowing this. It works.
@SeanBurton, A1(some_another_struct_a_variable) initializes A1 with some_another_struct_a_variable and A1() initializes A1 using default constructor. . Am I right ?
|
2

You can give constructor to struct just like class, and init it to 0

struct a
{
   int a1;
   int a2;
   int a3;
   a() : a1(0), a2(0), a3(0)
   {
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.