Paul Paul - 4 months ago 26
C++ Question

unordered_map with custom hashing/equal functions - functions don't get called

This is weird.. the following code (which I managed to compile thanks to Cassio Neri) is compiling without any error.. by the way either hashing_func nor key_equal_func do get called (the couts aren't showing in the console window)

#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <functional>

using namespace std;

unsigned long hashing_func(string key)
cout << "Hashing called";
unsigned long hash = 0;
for(int i=0; i<key.size(); i++)
hash += (71*hash + key[i]) % 5;
return hash;

template<class T> bool key_equal_fn(T t1, T t2)
return t1 == t2;

template <> bool key_equal_fn<string>(string t1, string t2)
cout << "Equal called";
return !(;

int main ()
unordered_map<string, string>::size_type n = 5;
unordered_map<string, string> mymap(n, (const std::hash<string> &)hashing_func,
(const std::equal_to<string> &)(function<bool(string,string)>(key_equal_fn<string>))) ;

bool case_insensitive = mymap.key_eq()("test","TEST");

mymap["paul"] = "jenna";
mymap["frank"] = "ashley";

if(mymap["paul"] == mymap["frank"])
cout << "equal" << endl;

return 0;

I'm using MSVC2012, any hint on what could be the problem?


The problem is that you need to pass the types of your hash function and hash_key_equal function to your unordered_map, and then the actual functions to the ctor of the map.

Your unordered_map definition should look like this:

    std::function<unsigned long(std::string)>,
    std::function<bool(std::string, std::string)>
> mymap(n, hashing_func, key_equal_fn<std::string>);

The unordered_map is a template and it looks like this:

    class Key,
    class T,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator<std::pair<const Key, T>>
> class unordered_map;

which means if you want to pass new Hash and KeyEqual functions you have to tell the template the types of these things.

Link isn't accessible anymore (Request Update): Live Example