Open In App

How to Find the Union of Two Maps in C++?

In C++, maps are associative containers that store key-value pairs. The union of two maps means combining their elements while ensuring that duplicate keys are handled appropriately. In this article, we will learn how to find the union of two maps in C++.

For Example,



Input:
mapA = {{'a', 1}, {'b', 2}};
mapB = {{'b', 3}, {'c', 4}};

Output:
Map After Union: 
a: 1
b: 3
c: 4

Merge Two Maps in C++

To find the union of two std::maps, we can use the std::map::insert function that accepts iterators pointing to the beginning and end of another map whose elements need to be added to the original map. Maps already stores the unique elements so there will be no issues regarding duplicates.

Syntax to Find the Union of Two Maps

map1.insert(map2.begin() , map2.end());

C++ Program to Merge Two Maps

The below program demonstrates how we can use std::map::insert() function to find union of two maps in C++.






// C++ program to illustrate how to find union of two maps
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
  
    // creating two maps to be merged
    map<char, int> mapA = { { 'a', 1 }, { 'b', 2 } };
    map<char, int> mapB = { { 'b', 3 }, { 'c', 4 } };
  
    // Merge elements from mapB into mapA
    mapA.insert(mapB.begin(), mapB.end());
  
    // Print the merged map
    for (const auto& pair : mapA) {
        cout << pair.first << ": " << pair.second << endl;
    }
  
    return 0;
}

Output
a: 1
b: 2
c: 4

Time Complexity: O(n + m), here n and m are the number of elements in the first and second map respectively.
Auxilliary Space: O(n + m)

Note: We can also std::map::merge function to find union of two maps while using C++ 17 and newer.

Article Tags :