Introduction
In this lab, we will create a C++ program to demonstrate the working of an Unordered Multiset in STL. We will learn about the concept of Unordered Multiset and its implementation in the C++ programming language.
In this lab, we will create a C++ program to demonstrate the working of an Unordered Multiset in STL. We will learn about the concept of Unordered Multiset and its implementation in the C++ programming language.
In this step, we will include the necessary header files for our program. We will include the iostream
and unordered_set
header files.
#include<iostream>
#include<unordered_set>
using namespace std;
In this step, we will define two functions to display the contents of an Unordered Multiset and a Vector.
void showMultiset(unordered_multiset<int> s)
{
unordered_multiset<int>::iterator i;
for (i = s.begin(); i != s.end(); i++)
{
cout << *i << " ";
}
}
void showVector(vector<int> v)
{
vector<int>::iterator i;
for (i = v.begin(); i != v.end(); i++)
{
cout << *i << " ";
}
}
In this step, we will declare an Unordered Multiset and fill it with some elements using the insert()
method.
unordered_multiset<int> s;
s.insert(50);
s.insert(30);
s.insert(50);
s.insert(80);
s.insert(30);
s.insert(60);
In this step, we will display the Unordered Multiset and its size using the showMultiset()
function and the size()
method.
cout << "\n\nThe number of elements in the Unordered Multiset are: " << s.size();
cout << "\n\nThe elements of the Unordered Multiset are: ";
showMultiset(s);
In this step, we will copy the elements of the Unordered Multiset to a Vector and sort the Vector. Then we will display the sorted elements of the Unordered Multiset using the showVector()
function.
vector<int> v(s.begin(), s.end());
sort(v.begin(), v.end());
cout << "\n\nThe elements of the Unordered Multiset after sorting using a vector are: ";
showVector(v);
In this step, we will run the code by compiling it using the g++
command and then executing it using the ./a.out
command.
g++ main.cpp -o main && ./main
The output should be:
The number of elements in the Unordered Multiset are: 6
The elements of the Unordered Multiset are: 50 30 80 50 30 60
The elements of the Unordered Multiset after sorting using a vector are: 30 30 50 50 60 80
In this lab, we learned about the concept of Unordered Multisets and their implementation in C++ using the STL library. We saw how to declare and initialize an Unordered Multiset, how to display its contents, and how to sort it using a Vector.
We hope you enjoyed this lab and found it useful for learning about Unordered Multisets in C++.