jeudi 26 novembre 2015

C++ - adding a hashmap to a struct

I want a struct that has an unordered_map as a member.
I also don't want to type out the type all the time, so I typedef it.

typedef std::unordered_map<std::string, int> HM;
struct A {
    HM myHm;
}

A *myA = new A();
HM hashmap = HM(); // empty hashmap
hashmap["1"] = 1;
myA->myHm = hashmap;

Of course this isn't correct.

I see examples of people doing std::unordered_map<std::string, int> HM;
And then immediately HM["1"] = 1;

First of all, I'm used to Java where std::unordered_map<std::string, int> HM; is just a type and if I want to add stuff to it, I need to instantiate it with ().

It seems that in C++, it's instantiated the moment I write std::unordered_map<std::string, int> HM;. Can anyone offer some insight into this?

Second, what is the correct way of doing what I want?

Aucun commentaire:

Enregistrer un commentaire