Horje
How to Insert Multiple Elements to a Multiset in C++?

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

  1. Create a range of elements to insert, either using another container or using an initializer list.
  2. 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++

// 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)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Find the Last Element in a Set in C++? How to Find the Last Element in a Set in C++?
How to Use Iterator with a Vector in C++? How to Use Iterator with a Vector in C++?
How to Add an Element to a Set in C++? How to Add an Element to a Set in C++?
How to Delete an Element from a Set in C++? How to Delete an Element from a Set in C++?
How to Replace an Element in a Vector in C++? How to Replace an Element in a Vector in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12