error for hash function of pair of ints

Unfortunately, this program has undefined behavior. C++11 §17.6.4.2.1: A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited. hash<pair<int,int>> depends on primitive and standard … Read more

pair pair as key of unordered_map issue

This happens because there is no specialization for std::tr1::hash<Key> with Key = std::pair<int, int>. You must to specialize std::tr1::hash<Key> with Key = std::pair<int, int> before declaring tr1::unordered_map<Pair,bool> h;. This happens because std don’t know how to hash a pair<int, int>. Following there is a example of how to specialize std::tr1::hash<> template <> struct std::tr1::hash<std::pair<int, int> … Read more

How does C++ STL unordered_map resolve collisions?

The standard defines a little more about this than most people seem to realize. Specifically, the standard requires (§23.2.5/9): The elements of an unordered associative container are organized into buckets. Keys with the same hash code appear in the same bucket. The interface includes a bucket_count that runs in constant time. (table 103). It also … Read more

Why is std::unordered_map slow, and can I use it more effectively to alleviate that?

The standard library’s maps are, indeed, inherently slow (std::map especially but std::unoredered_map as well). Google’s Chandler Carruth explains this in his CppCon 2014 talk; in a nutshell: std::unordered_map is cache-unfriendly because it uses linked lists as buckets. This SO question mentioned some efficient hash map implementations – use one of those instead.

unordered_map hash function c++

This is an unfortunate omission in C++11; Boost has the answer in terms of hash_combine. Feel free to just paste it from them! Here’s how I hash pairs: template <class T> inline void hash_combine(std::size_t & seed, const T & v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> … Read more