How to Insert an Element into a Multiset in C++?
Last Updated :
12 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
multiset< int > myMultiset = { 1, 2, 4, 5, 6, 7, 8 };
cout << "Multiset Before Insertion:" ;
for ( auto & element : myMultiset) {
cout << element << " " ;
}
cout << endl;
int elementToInsert = 3;
myMultiset.insert(elementToInsert);
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)
Share your thoughts in the comments
Please Login to comment...