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++ Program to show how to insert multiple elements into
// a multiset
#include <iostream>
#include <set>
#include <vector>
using namespace std;
// Driver Code
int main()
{
multiset<int> myMultiset = { 10, 20, 30 };
vector<int> elements = { 40, 60, 50 };
// Insert a range of elements
myMultiset.insert(elements.begin(), elements.end());
// Display the multiset
for (const auto& element : myMultiset) {
cout << element << ' ';
}
return 0;
}
Output
10 20 30 40 50 60
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)