How to create an unordered_map of pairs in C++?


In this tutorial, we will be discussing a program to understand how to create an unordered map of pairs in C++.

Unordered maps are the ones that don't contain hash function for the pairs by default. If we want a hash value for a particular pair, it needs to be passed on explicitly.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//to hash any given pair
struct hash_pair {
   template <class T1, class T2>
   size_t operator()(const pair<T1, T2>& p) const{
      auto hash1 = hash<T1>{}(p.first);
      auto hash2 = hash<T2>{}(p.second);
      return hash1 ^ hash2;
   }
};
int main(){
   //explicitly sending hash function
   unordered_map<pair<int, int>, bool, hash_pair> um;
   //creating some pairs to be used as keys
   pair<int, int> p1(1000, 2000);
   pair<int, int> p2(2000, 3000);
   pair<int, int> p3(2005, 3005);
   um[p1] = true;
   um[p2] = false;
   um[p3] = true;
   cout << "Contents of the unordered_map : \n";
   for (auto p : um)
      cout << "[" << (p.first).first << ", "<< (p.first).second << "] ==> " << p.second << "\n";
   return 0;
}

Output

Contents of the unordered_map :
[1000, 2000] ==> 1
[2005, 3005] ==> 1
[2000, 3000] ==> 0

Updated on: 25-Feb-2020

730 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements