Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Difficulty Level : Easy
  • Last Updated : 28 Oct, 2021

Tuple – A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed.

Unordered Map does not contain a hash function for a tuple. So if we want to hash a tuple then we have to explicitly provide it with a hash function that can hash a tuple.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

unordered_map can take up to 5 arguments:

  • Key: Type of key values.
  • Value: Type of value to be stored against the key.
  • Hash Function: A function that is used to hash the given key. If not provided it uses the default hash function.
  • Pred: A function that is used so that no two keys can have the same hash values.
  • Alloc: An object used to define the memory model for the map.

hash_function can be anything, given that it can hash the given key.



Syntax:

unordered_map<tuple<data_type, data_type, data_type>, data_type, hash_function> map_of_tuple;  

C++




// CPP program to demonstrate implementation
// of unordered_map for a tuple.
  
#include <bits/stdc++.h>
using namespace std;
  
// A hash function used to hash a tuple
struct hash_tuple {
  
    template <class T1, class T2, class T3>
  
    size_t operator()(
        const tuple<T1, T2, T3>& x)
        const
    {
        return get<0>(x)
               ^ get<1>(x)
               ^ get<2>(x);
    }
};
  
int main()
{
  
    // Sending the hash function
    // as a third argument
    unordered_map<tuple<int, int, int>,
                  bool, hash_tuple>
        mapOfTuple;
  
    // Creating some tuples to be used as keys
    tuple<int, int, int> t1(100, 200, 300);
    tuple<int, int, int> t2(400, 500, 600);
    tuple<int, int, int> t3(700, 800, 900);
  
    // Inserting values
    // in the unordered_map
    mapOfTuple[t1] = true;
    mapOfTuple[t2] = false;
    mapOfTuple[t3] = true;
  
    cout << "Contents of the unordered_map: \n";
    for (auto p : mapOfTuple)
        cout << "[" << get<0>(p.first) << ", "
             << get<1>(p.first) << ", "
             << get<2>(p.first)
             << "] ==> " << p.second << "\n";
  
    return 0;
}
Output
Contents of the unordered_map: 
[700, 800, 900] ==> 1
[100, 200, 300] ==> 1
[400, 500, 600] ==> 0

Note: It is not required to pass a hash function in the map which is a self-balancing BST.  In order words, map<tuple<data_type, data_type, data_type>, data_type> mp works fine.




My Personal Notes arrow_drop_up
Recommended Articles
Page :