C++ – How to use stdext::hash_map where the key is a custom object

chashmapstl

Using the STL C++ hash_map…

class MyKeyObject
{
    std::string str1;
    std::string str2;

    bool operator==(...) { this.str1 == that.str1 ... }
};

class MyData
{
    std::string data1;
    int data2;
    std::string etcetc;
};

like this…

MyKeyObject a = MyKeyObject(...);
MyData b = MyData(...);

stdext::hash_map <MyKeyObject, MyData> _myDataHashMap;
_myDataHashMap[ a ] = b;

I get a whole load of errors. Here are the first three…

Error 1 error C2784: 'bool
std::operator <(const
std::_Tree<_Traits> &,const
std::_Tree<_Traits> &)' : could not
deduce template argument for 'const
std::_Tree<_Traits> &' from 'const
MyKeyObject' c:\program files\microsoft
visual studio
8\vc\include\functional 143

Error 2 error C2784: 'bool
std::operator <(const
std::basic_string<_Elem,_Traits,_Alloc>
&,const _Elem *)' : could not deduce
template argument for 'const
std::basic_string<_Elem,_Traits,_Alloc>
&' from 'const
Tasking::MyKeyObject' c:\program
files\microsoft visual studio
8\vc\include\functional 143

Error 3 error C2784: 'bool
std::operator <(const _Elem *,const
std::basic_string<_Elem,_Traits,_Alloc>
&)' : could not deduce template
argument for 'const _Elem *' from
'const MyDataObject' c:\program
files\microsoft visual studio
8\vc\include\functional 143

If I set the key to something simple like an int all is well.

What am I doing wrong?! Maybe I need to do something with templates?

Is there a better (quicker?) way of accessing data using a custom key object like this?

Best Answer

To use a hash table, you need to specify a hash function. You need to create a function object which represents a function that takes a MyKeyObject object and returns a size_t. Then you pass the functor as the second argument after the initial size:

hash_map <MyKeyObject, MyData> _myDataHashMap(initial_size, YourHashFunctor());

Alternately, you can write your hash function as the template specialization of the hash<T> functor for your type; that way you don't need to pass in a custom hash function.

I don't know why you are getting those errors specifically. Perhaps it's trying to use the your object as the hash code or something? In any case it should not work without a hash function. Hash functions are pre-defined for the integer types and strings.

Related Topic