×

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values.

Associative containers implement instantly searchable sorted data structures with O(log n) complexity.

In a multiset, an element is also identified by its value (the value is itself the key, of type T). A multiset's elements can be added to or deleted from the container, but their values cannot be changed once they are inside the container (they are always const).

A multiset's internal comparison object always indicates the strict weak ordering criterion that must be followed while sorting the elements internally (of type Compare).

Multiset containers provide direct iteration on subsets depending on their order but are typically slower than unordered multiset containers to access individual pieces by their key.

The most common way to implement multisets is via binary search trees.

Associated multiset functions:

  • end() -  This function is used to return a theoretical element that follows the last element, which is present in the Multiset through an iterator in O(1)
  • begin() - This function is used to return the first element in the Multiset through an iterator -> O(1)
  • size() - Returns how many elements are in the multiset -> O(1)
  • max size() - Returns how many elements the multiset can hold -> O(1)
  • empty () - Checks to see if the multiset is empty and inserts in O(1) time (x) Removes all elements from the multiset -> O(n)
  • erase(x); - Inserts element x into the multiset -> O(log n)
  • clear (); - Removes all instances of x -> O (log n)

Implementation of Multi set

Example 1:

#include <iostream>
#include <set>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
    multiset<int> mse;
    multiset<int>::iterator it, it1;
    int ch, item;
    while (1)
    {
        cout<<"\n*************"<<endl;
        cout<<"Implementation of Multiset in STL"<<endl;
        cout<<"\n*************"<<endl;
        cout<<"1.Insert an Element into the Multiset"<<endl;
        cout<<"2.Delete an Element from the Multiset"<<endl;
        cout<<"3.Find out the Element in a Multiset"<<endl;
        cout<<"4.Count the Elements with a particular key"<<endl;
        cout<<"5.Size of the Multiset"<<endl;
        cout<<"6.Display Multiset"<<endl;
        cout<<"7.Exit"<<endl;
        cout<<"Enter your Choice: ";
        cin>>ch;
        switch(ch)
        {
        case 1:
            cout<<"Enter value to be inserted: ";
            cin>>item;
            if (mse.empty())
                it1 = mse.insert(item);
            else
                it1 = mse.insert(it1, item);
            break;
        case 2:
            cout<<"Enter value to be deleted: ";
            cin>>item;
            mse.erase(item);
            break;
        case 3:
            cout<<"Enter element to find ";
            cin>>item;
            it = mse.find(item);
            if (it != mse.end())
                cout<<"Element found"<<endl;
            else
                cout<<"Element not found"<<endl;
            break;
        case 4:
            cout<<"Enter element to be counted: ";
            cin>>item;
            cout<<item<<" appears "<<mse.count(item)<<" times."<<endl;
            break;
        case 5:
            cout<<"Size of the Multiset: "<<mse.size()<<endl;
            break;
        case 6:
            cout<<"Elements of the Multiset:  ";
            for (it = mse.begin(); it != mse.end(); it++)
                cout<<*it<<"  ";
            cout<<endl;
            break;
		case 7:
            exit(1);
	        break;
        default:
            cout<<"Wrong Choice Entered"<<endl;
        }
    }
    return 0;
}

Output:

How is multiset implemented in c++?

Example 2:

#include <iostream>
#include <bits/stdc++.h>


using namespace std;


void show(multiset<int> s)
{


    multiset<int>::iterator i;


    for (i = s.begin(); i != s.end(); i++)
    {
        cout << *i << "  ";
    }


    cout << endl;
}


int main()
{
    cout << "  Program to illustrate the working of a Multiset, in CPP  \n";


    cout << "*** Multisets are similar to set, with an exception that multiple elements can have same values. *** \n\n";


    //Set declaration (Set of integers)
    multiset<int> s;


    //Filling the elements by using the insert() method.
    cout << "\n\nFilling the Multiset with integers in random order."; //Multiset automatically stores them in order


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


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


    cout << "\n\nThe elements of the Multiset are: ";
    show(s);


    multiset<int>::iterator it;
    s.erase(s.begin(), s.find(54));


    cout << "\n\nAfter deleting all the elements which are less than 54, the Multiset become as : ";


    for (it = s.begin(); it != s.end(); it++)
    {
        cout << " " << *it;
    }


    cout << "\n\n\n";


    return 0;
}

Output:

How is multiset implemented in c++?

Example 3:

#include <iostream>
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    multiset<int, greater<int> > g1;
 
    // insert elements in random order
    g1.insert(40);
    g1.insert(30);
    g1.insert(60);
    g1.insert(20);
    g1.insert(50);
 
    // 50 will be added again to
    // the multiset unlike set
    g1.insert(50);
    g1.insert(10);
 
    // printing multiset g1
    multiset<int, greater<int> >::iterator itr;
    cout << "\nThe multiset g1 is : \n";
    for (itr = g1.begin(); itr != g1.end(); ++itr) {
        cout << *itr << " ";
    }
    cout << endl;
 
    // assigning the elements from g1 to g2
    multiset<int> g2(g1.begin(), g1.end());
 
    cout << "\nThe multiset g2 \n"
            "after assign from g1 is : \n";
    for (itr = g2.begin(); itr != g2.end(); ++itr) {
        cout << *itr << " ";
    }
    cout << endl;
 
    // remove all elements up to element
    // with value 30 in g2
    cout << "\ng2 after removal \n"
            "of elements less than 30 : \n";
    g2.erase(g2.begin(), g2.find(30));
    for (itr = g2.begin(); itr != g2.end(); ++itr) {
        cout << *itr << " ";
    }
 
    // remove all elements with value 50 in gquiz2
    int num;
    num = g2.erase(50);
    cout << "\ng2.erase(50) : \n";
    cout << num << " removed \n";
    for (itr = g2.begin(); itr != g2.end(); ++itr) {
        cout << *itr << " ";
    }
 
    cout << endl;
 
    // lower bound and upper bound for multiset g1
    cout << "\ng1.lower_bound(40) : \n"
         << *g1.lower_bound(40) << endl;
    cout << "g1.upper_bound(40) : \n"
         << *g1.upper_bound(40) << endl;
 
    // lower bound and upper bound for multiset g2
    cout << "g2.lower_bound(40) : \n"
         << *g2.lower_bound(40) << endl;
    cout << "g2.upper_bound(40) : \n"
         << *g2.upper_bound(40) << endl;
 
    return 0;
}

Output:

The multiset g1 is : 
60 50 50 40 30 20 10 


The multiset g2 
after assign from g1 is : 
10 20 30 40 50 50 60 


g2 after removal 
of elements less than 30 : 
30 40 50 50 60 
g2.erase(50) : 
2 removed 
30 40 60 


g1.lower_bound(40) : 
40
g1.upper_bound(40) : 
30
g2.lower_bound(40) : 
40
g2.upper_bound(40) : 
60

Related Topics

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.