How to Insert Multiple Elements to a Multiset in C++?
Last Updated :
27 Feb, 2024
In C++, a multiset is a container that stores elements in a specific order. Multiple elements can have the same values. In this article, we will learn how to insert multiple elements into a multiset in C++.
Example:
Input:
myMultiset = {1, 4, 5, 9};
ElementsToBeAdded = {2, 3, 4}
Output:
myMultiset = {1, 2, 3, 4, 4, 5, 9}
Insert Multiple Elements to a Multiset in C++
To add multiple elements into a std::multiset in C++, you can use the std::multiset::insert()
with iterators of the range from which you want to insert the elements.
Approach
- Create a range of elements to insert, either using another container or using an initializer list.
- Use the
insert()
function with the beginning and end iterators of the range to insert the elements into the multiset.
C++ Program to Insert Multiple Elements into a Multiset
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
multiset< int > myMultiset = { 10, 20, 30 };
vector< int > elements = { 40, 60, 50 };
myMultiset.insert(elements.begin(), elements.end());
for ( const auto & element : myMultiset) {
cout << element << ' ' ;
}
return 0;
}
|
Time Complexity: O(M log N), where N is the size of the multiset and M is the number of new elements.
Space Complexity: O(M)
Share your thoughts in the comments
Please Login to comment...