Open In App

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

In C++, a map is a container that stores key-value pairs in an ordered or sorted manner. Finding the difference between two maps involves determining the elements that are present in one map but not in the other. In this article, we will learn how to find the difference between two Maps in C++.

Example :



Input:
myMap1 = { {1: "C++"}, {2: "Java"}, {3: "Python"} }
myMap2 = { {2: "Java"}, {3: "C"}, {4: "JavaScript"} }

Output :
Difference between map1 and map2:
Key: 1, Value: C++
Key: 3, Value: Python
Key: 4, Value: JavaScript

Find the Difference of Two Maps in C++

To find the difference between the two maps, we will start checking in both of the maps, where the difference is. We can do this by simply iterating through both of the maps.

Approach

C++ Program to Find the Difference of Two Maps




// C++ Program to illustrate how to find the difference of
// two maps
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Initialize two maps
    map<int, string> map1
        = { { 1, "C++" }, { 2, "Java" }, { 3, "Python" } };
    map<int, string> map2 = { { 2, "Java" },
                              { 3, "Python" },
                              { 4, "JavaScript" } };
  
    // Create a map to store the difference
    map<int, string> diff;
  
    // Find the difference of the two maps
    for (auto& pair : map1) {
        if (map2.find(pair.first) == map2.end()) {
            diff.insert(pair);
        }
    }
  
    // Print the difference of the two maps
    for (auto& pair : diff) {
        cout << "{" << pair.first << ", " << pair.second
             << "}, ";
    }
    cout << endl;
  
    return 0;
}

Output

{1, C++}, 

Time Complexity : O(N logM, M logN), where N and M are the sizes of the input maps map1 and map2, respectively.
Auxiliary Space: O(N + M)


Article Tags :