Defining a hash function in TR1 unordered_map inside a struct

Alexandros picture Alexandros · Mar 25, 2011 · Viewed 6.9k times · Source

According to this, it is possible to define an equality function in a TR1 unordered_map like this:

#include <tr1/unordered_map>
using namespace std;
using namespace std::tr1;
struct foo{
    ...
    bool operator==(const foo& b) const{
        return ..;
    }
};

unordered_map<foo,int> map;

Is it possible to define the hash function the same way?

Answer

Jerry Coffin picture Jerry Coffin · Mar 25, 2011

If you want to change the default hashing (or, more often, provide hashing for a type that isn't currently supported), you provide a specialization of std::tr1::hash<T> for your key-type:

namespace std { 
namespace tr1 { 
    template<>
    struct hash<typename my_key_type> {
        std::size_t operator()(my_key_type const &key) {
            return whatever;
        }
    };
}
}

Note that specializing an existing template for a user-defined type is one of the rare cases where you specifically are allowed to write code in namespace std.