Open In App

How to Insert an Element into a Multiset in C++?

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

In C++, multisets are associative containers similar to sets, but unlike sets, they allow the users to store duplicate elements. In this article, we will learn how we can insert an element into a multiset in C++.

Example:

Input:
myMultiset ={1,2,4,5,6,7,8}

Output:
myMultiset = {1,2,3,4,5,6,7,8} // inserted element 3

Insert an Element into a Multiset in C++

To insert an element into a std::multiset we can simply use the std::multiset::insert() function. The multiset::insert() is a built-in member function in the multiset container. Since the elements are always in sorted order, the newly inserted elements should be added to their sorted order place.

Syntax of std::multiset::insert()

multiset_name.insert(element)

C++ Program to Insert an Element into a Multiset

C++




// C++ program to Insert an Element from a Multiset
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    multiset<int> myMultiset = { 1, 2, 4, 5, 6, 7, 8 };
  
    // Printing the elements of the multiset before
    // insertion
    cout << "Multiset Before Insertion:";
    for (auto& element : myMultiset) {
        cout << element << " ";
    }
    cout << endl;
  
    // declare the element you want to insert
    int elementToInsert = 3;
  
    // insert the element using insert() function
    myMultiset.insert(elementToInsert);
  
    // Printing the elements of the multiset after insertion
    cout << "Multiset After Insertion:";
    for (auto& element : myMultiset) {
        cout << element << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Multiset Before Insertion:1 2 4 5 6 7 8 
Multiset After Insertion:1 2 3 4 5 6 7 8 

Time Complexity: O(log N), where N is the number of elements in the multiset.
Auxilary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads