tags:

views:

819

answers:

3

Newbie question here.

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

map myMap;

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

Thanks.

+6  A: 
#include <map>

std::map<int, MyClass> myMap;

MyClass foo;
myMap[5] = foo;
myMap[5].bar = 10;

You do need MyClass to be default- and copy- constructible, so it can be created (if you use, e.g., myMap[5]) and copied into the map.

Jesse Beder
I think you only need the default constructor if you use operator[].
Troubadour
Yes, I think that's correct.
Jesse Beder
Maybe even add "typedef std::map<int, MyClass> MyMapType;"
Bill
while using [] operator with map we should take care if already this key exist, otherwise earlier value will be replaced by new value , which may lead to a crisis
sat
+1  A: 

Yes the only condition are:

  • The key Type is comparable (Good)
  • The value Type is copy constructable ?

So you just need to make sure you are object is copy constructable so that it can be copied into the map.

Martin York
Of course you don't even need the copy constructor if only storing pointers to instances of the class in the map instead.
Troubadour
@Troubadour: Sort of true. But in that case you are storing a pointer. The equivalent of copy constructor for a POD type is simple assignment (so I always equate the two as the same) and this just makes a copy of the pointer. The other side affect of this is the map owns the pointer not the object. The map will release the pointer but not the object it is pointing at (so no delete). For this we have boost::ptr_map<int,MyClass>
Martin York
A: 

you should use like this

typedef std::map myMapType;

myMapType myMap;

But be careful when inserting your class in this as if you insert more than one time for same key, you will never get a notice :

Call myMapType::iterator itr myMap.find(key) , depending upon return type and your program requirments you can procced.

Like wise try to avid access any element using [] operator like

 somefunc(myMap[10]);

As you will not get an error from map even there was noting inserted for key 10

sat