Open In App

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

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

In C++, an unordered multiset is a container that stores elements in no particular order, allowing fast retrieval of individual elements based on their value, much like unordered set containers, but allowing different elements to have equivalent values. In this article, we will learn how to create an unordered multiset of tuples in C++.

Example:

Input:
tuple1 = (1, Apple, 10.5) 
tuple2 = (2, Mango, 20.5) 
tuple3 = (3, Guava, 30.5)

Output:
Unordered Multiset Elements:
Tuple 1: (1, Apple, 10.5)
Tuple 2: (2, Mango, 20.5)
Tuple 3: (3, Guava, 30.5)

Unordered Multiset of Tuples in C++

Unordered Multiset of any type can be created by passing the type as the template parameters but it doesn’t have built in support for tulple. But we can still create an unordered multiset container of tuples by passing std::tuple as template parameter along with a custom hash function. We can then insert the data into this container using make_tuple() method and std::unordered_multiset::insert() method.

Syntax to Create a Multiset of Tuples

unordered_multiset <tuple <dataType1, dataType2,....>, hashFunction> name;

C++ Program to Create an Unordered Multiset of Tuples

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

C++
// C++ Program to illustrate how to create an unordered
// multiset of tuples
#include <iostream>
#include <tuple>
#include <unordered_set>
using namespace std;

struct hashFunc {
public:
    size_t operator()(const tuple<int, string>& tup) const
    {
        return get<0>(tup);
    }
};

int main()
{
    // Initialize two tuples
    tuple<int, string> myTuple1 = make_tuple(1, "C++");
    tuple<int, string> myTuple2 = make_tuple(2, "Java");

    // Create an unordered multiset of tuples
    unordered_multiset<tuple<int, string>, hashFunc>
        myMultiset;
    myMultiset.insert(myTuple1);
    myMultiset.insert(myTuple2);

    // Print the unordered multiset of tuples
    for (auto& tuple : myMultiset) {
        cout << "{" << get<0>(tuple) << ", "
             << get<1>(tuple) << "}, ";
    }
    cout << endl;

    return 0;
}

Output
{2, Java}, {1, C++}, 

Time Complexity: O(N), here N is the number of tuples in the set
Auxiliary Space: O(N * M), where M is the number of elements in the tuple.




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads