Last Updated : 23 Jul, 2025
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
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;
}
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)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4