This post will discuss how to use std::pair as a key to std::unordered_map in C++.

The std::map uses a predicate for key comparison, whose type is specified as the third template parameter of std::map. The default value for this parameter is std::less, which will delegate to operator<. Since operator< is defined for pairs, the following declaration works in C++:

 
On the other hand, std::unordered_map throws a compilation error when std::pair is used as a key.

 
This is because std::unordered_map uses std::hash for computing hash value for its keys and there is no specialization of std::hash for std::pair in the C++ standard library. If we want to use a pair as key to std::unordered_map, we can follow any of the following approaches:

1. Define specialization for std::hash function

Here, the idea is to define our own specialization for std::hash that works with std::pair.

Download  Run Code

Output:

{Java,Java 8}, 2014
{Java,Java 7}, 2011
{Java,Java 9}, 2017
{C++,C++17}, 2017
{C++,C++14}, 2014
{C++,C++11}, 2011

 
The above code uses XOR as a hash combination function for simplicity. XOR should be avoided as XOR maps identical values and symmetric pairs to 0 (x ^ x == y ^ y == 0, x ^ y == y ^ x). This would end up with far too many collisions in the real world. For production code, we should shift/rotate one of the hashes before XORing.

2. Using boost Library

Another good alternative is to use the boost::hash from Boost.Functional, which can be used to hash integers, floats, pointers, strings, arrays, pairs, and the STL containers.

Download Code

Output:

{Java,Java 8}, 2014
{Java,Java 9}, 2017
{Java,Java 7}, 2011
{C++,C++17}, 2017
{C++,C++14}, 2014
{C++,C++11}, 2011

That’s all about using std::pair as key to std::unordered_map in C++.

 
Also See:

3 ways to use std::pair as a key to std::map in C++