C ++ STL map with user class of the second type

I would like to create a map with int and my own custom class. Is there any way to do this?

map<int, MyClass> myMap; 

If not, how do I do this? Basically, I want id (or preferably enum ) to point to my own custom class. In most other languages, this will be a simple hash.

+3
source share
3 answers
 #include <map> std::map<int, MyClass> myMap; MyClass foo; myMap[5] = foo; myMap[5].bar = 10; 

You will need MyClass to create by default and to copy, so you can create it (if you use, for example, myMap[5] ) and copy it to the map.

+9
source

Yes, the only condition:

  • Key type comparable (good)
  • Value Type copy construct?

Thus, you just need to make sure that you are an object, which is a copy that can be copied to the card.

+3
source

you should use this as

typedef std :: map myMapType;

myMapType myMap;

But be careful when inserting your class into this, as if you inserted more than once for the same key, you will never receive a notification:

Call myMapType :: iterator itr myMap.find (key), depending on the type of return and your programming requirements that you can fulfill.

Like a wise attempt to request access to any element using the [] operator, for example

  somefunc(myMap[10]); 

Since you will not get an error on the map, even there it was marked inserted for key 10

0
source

All Articles