How to Find the Union of Two Multimaps in C++?
In C++, finding the union of two multimaps consists of combining the elements from both multimap collections while considering the duplicates as a multimap allows multiple values to have the same key. In this article, we will learn to find the union of two multimaps in C++.
Example:
Input: multi1 = {1, "Java"}, {2, "Python"}, {3, "C++"}, {4, "JavaScript"} mutli2 = {2, "Python"}, {4, "JavaScript"}, {5, "TypeScript"} Output: Union MultiMap: 1: Java 2: Python 2: Python 3: C++ 4: JavaScript 4: JavaScript 5: TypeScript
Finding Union of Two Multimaps in C++
To find the union of two multimaps in C++, we can insert all the elements of the two multimaps in the new multimap container using std::multimap::insert() function that inserts elements from a range to the multimap container.
C++ Program to Find the Union of Two Multimaps
The below program demonstrates how we can use the std::insert() function to find the union of two multimaps in C++ STL.
// C++ Program to illustrate how to find the union of two multimaps
#include <iostream>
#include <map>
using namespace std;
int main()
{
// Defining multimap1
multimap<int, string> multimap1 = { { 1, "Java" },
{ 2, "Python" },
{ 3, "C++" },
{ 4, "JavaScript" } };
// Defining multimap2
multimap<int, string> multimap2 = { { 2, "Python" },
{ 4, "JavaScript" },
{ 5, "TypeScript" } };
// Finding union between multimap1 and multimap2
multimap<int, string> unionMap = multimap1;
unionMap.insert(multimap2.begin(), multimap2.end());
// Printing union
cout << "Union MultiMap:" << endl;
for (const auto& pair : unionMap) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
Output
Union MultiMap: 1: Java 2: Python 2: Python 3: C++ 4: JavaScript 4: JavaScript 5: TypeScript
Time complexity: O(N+M), where N and M are the size of the two multimaps.
Auxiliary Space: O(N+M)
Note: We can also use the
std::merge
function from the<algorithm>
library to find the union of two multimaps in C++.