I came across this very old question, trying to find the same answer, and finding existing answers is not very useful. We are currently using unordered_map if we want a hash map, and the best way to make your MyKeyObject class useful as a key in hash_map in general is to define a hash function for the class and tell the standard library this hash function for mappings. This means that we can create a template template without providing a hash function.
in the "Unordered Associative Containers in C ++" section gives a simple example, I disabled it a bit and applied it to your case. First, we define a simple hash function as a member method:
#include <functional> class MyKeyObject { private: std::string str1; std::string str2; public: inline size_t hash() const { return std::hash<std::string>()(str1) ^ std::hash<std::string>()(str2); } inline bool operator==(const MyKeyObject& other) const { return str1 == other.str1 && str2 == other.str2; } };
To make a hash function, we xor the hashes of all the contained objects together. This is done using std::hash , a template that must be created using a child type. Please note: we cannot use this as the third template parameter for unordered_map. Note also the const-equals operator.
Now we need to tell the standard library that this is a hash function that will be used for MyKeyObject values:
namespace std { template <> class hash<MyKeyObject> { public: size_t operator()(const MyKeyObject &aMyKeyObject) const { return aMyKeyObject.hash(); } }; }
This adds the template specialization to the std::hash template std::hash , providing a hash statement for the MyKeyObject class. In the example, there is no wikipedia page that directly defines the hash here, and does not call a hash function that is a member of the object, but if the hash function needs to access private members, this will not work.
Now you can use MyKeyObject in unordered_map like this:
std::unordered_map<MyKeyObject, MyData> _myDataHashMap;
(verified with clang / xcode)