Open In App

How to Create a Unordered Multimap of Tuples in C++?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an unordered multimap container stores key-value pairs in no particular order. Unlike a map, an unordered multimap allows multiple values to be associated with a single key. In this article, we will learn how to create an unordered multimap of tuples in C++.

For Example,

Input: 
myPair1 = { "apple", make_tuple(1, "red") }
myPair2 = { "banana", make_tuple(2, "yellow") }

Output: 
unordered_Multimap:
apple 1 red
banana 2 yellow

Create an Unordered Multimap of Tuples in C++

To create an unordered multimap where tuples are values, we will have to define the type of the key during the declaration. After that, we can insert the elements using make_pair() with the unordered_multimap::insert() function.

Syntax to Declare Unordered Multimap of Tuples

multimap<keyType, tuple<dataType1, dataType2, dataType3,...> > multimapName;

Note: To create an unordered multimap where tuples are keys, we will need to pass a custom hashing function as another template parameters as there is no default hashing function for tuples in the map containers family.

C++ Program to Create an Unordered Multimap of Tuples

The below example demonstrates how we can create an unordered multimap of tuples in C++ STL.

C++
// C++ program to create a multimap of tuples using
// make_tuple

#include <iostream>
#include <tuple>
#include <unordered_map>
using namespace std;

int main()
{
    // Creating a multimap of string and tuple
    unordered_multimap<string, tuple<int, string> >
        myMultimap;

    // Inserting key-value pairs into the multimap
    myMultimap.insert({ "apple", make_tuple(1, "red") });
    myMultimap.insert(
        { "banana", make_tuple(2, "yellow") });
    myMultimap.insert({ "cherry", make_tuple(3, "red") });

    // Displaying the multimap elements
    cout << "Unordered Multimap: " << endl;
    for (auto it = myMultimap.begin();
         it != myMultimap.end(); ++it) {
        cout << it->first << " " << get<0>(it->second)
             << " " << get<1>(it->second) << endl;
    }

    return 0;
}

Output
Unordered Multimap: 
cherry 3 red
banana 2 yellow
apple 1 red

Time Complexity: O(N), here N is the number of tuples.
Auxiliary Space: O(N)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads