Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an stl map if I plan to use arbitrary class objects as the key?

I'm new to STL. The thing stumping me about using a map to store arbitrary objects:

std::map<MyClassObj, MyDataObject> MyMap;

is how I find objects. How would MyMap.find (MyClassObjInstance) work for instance? Do I need to implement my own iterator and provide some standard functions which would include some equivalence function? Any examples would be appreciated.

Is there another method to store an associated list of arbitrary objects using standard libraries? I'm already using stl to maintain platform portability, and would prefer not to add another library dependency like BOOST.

like image 326
AlanKley Avatar asked Sep 04 '09 17:09

AlanKley


1 Answers

std::map has a third template argument, after key and value, to denote what function is going to be used to compare keys. By default, it is std::less, which in it's turn uses operator<. So if your class has an operator<, it's ok, else you can provide a comparator of your own.

like image 76
xtofl Avatar answered Oct 11 '22 22:10

xtofl