c++ - Passing custom class object as a value into STL map -
i want pass object of custom class value stl map. how do that..?
here code:
class demo { int a, b,c,d,e; } // here how declare map: map<int, demo*> my_map; this how, using function:
demo *ptr = null; ptr = new demo; here how inserting map
my_map.insert(make_pair(int, ptr); // delete current instance delete ptr; is correct way..?
actually, no. if want store demo objects in map, should use map<int, demo>. leave resource management std::map. also, using delete ptr destroy created object, , my_map[index] invalid pointer.
just use my_map.insert(make_pair(myindex, mydemoobject));.
also note using my_map[myindex] create object given index if doesn't exist, can following:
std::map<int, demo> my_map; my_map[1].a = 42; my_map[2].b = 1337; my_map[3].c = 314159; my_map[4].d = 23;
Comments
Post a Comment