C++ Multiset in STL

C++C++Beginner
Practice Now

Introduction

In this lab, we will learn how to implement Multiset from the Standard Library (STL) in C++. A Multiset is similar to a Set in that it stores unique values, but, it differs from the Set as it allows duplicates and does not provide the indexing facilities associated with vector .


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") subgraph Lab Skills cpp/variables -.-> lab-96232{{"`C++ Multiset in STL`"}} cpp/data_types -.-> lab-96232{{"`C++ Multiset in STL`"}} cpp/operators -.-> lab-96232{{"`C++ Multiset in STL`"}} end

Create a C++ file in project directory

We will create a new file named main.cpp in the ~/project directory using the following command:

touch ~/project/main.cpp

Add the header files

Add the following header files for Multiset, Input/Output Stream, Standard Library and Iterator as shown in the example below:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

Declare the Multiset

Declare a Multiset of integer values, as shown below:

multiset<int> s;

Insert values into the Multiset

Insert elements into the Multiset using the insert() method, as shown in the example code below. It will insert 5, 39, 5, 82, 39, and 54 into the Multiset:

s.insert(5);
s.insert(39);
s.insert(5);
s.insert(82);
s.insert(39);
s.insert(54);

Print Size of Multiset and Traverse Multiset

Print the number of elements in the Multiset by accessing the size() property and traverse all the elements of the Multiset using an iterator, as shown below:

cout << "The number of elements in the Multiset : " << s.size() << "\n";

multiset<int>::iterator it;
cout << "\nElements of the Multiset : ";
for (it = s.begin(); it != s.end(); it++)
    cout << *it << " ";
cout << endl;

Delete Elements Less Than X

Delete all elements less than a given x value using the erase() method. The erase() method deletes all elements from the beginning of the Multiset to the given value, except the element with the given value, as shown below:

s.erase(s.begin(), s.find(x));

Run and Compile the Program

Compile the program using the terminal. Use the following command to compile the program:

g++ main.cpp -o main && ./main

Check the Output

After successfully running the program, you will get the following output:

The number of elements in the Multiset : 6

Elements of the Multiset : 5 5 39 39 54 82

Summary

This lab provided an overview of Multisets in C++ using STL. We covered how to declare a Multiset, insert values into it, and explored its methods. We also learned how to delete elements less than a specific value and traverse through the Multiset using iterators. Finally, we ran and compiled the code using the terminal to check the output.

Other C++ Tutorials you may like