Open In App

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

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • We will iterate through the first map to check which element is different from the second map by comparing the key and values of two elements of both maps.
  • We will push the different elements to another map container that will store the difference of two maps.
  • In the second iteration, we will check in the second map for the elements that are different from the first map.
  • We will then push the different elements to the map that contains the different elements form the first map.

C++ Program to Find the Difference of Two Maps

C++




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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads