Open In App

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

In C++, a map is a container that stores elements in a mapped fashion. Each element has a key value and a mapped value. The symmetric difference between two sets is formed by the elements that are present in one of the sets, but not in the other.  In this article, we will learn how to find the symmetric difference of two maps in C++.

Example:



Input: 
map1 = {{“apple”, 1}, {“banana”, 2}, {“cherry”, 3}}; 
map2 = {{“banana”, 2}, {“cherry”, 3}, {“date”, 4}};

Output: 
Symmetric_difference: {{“apple”, 1}, {“date”, 4}}

Finding Symmetric Difference of Two Maps in C++

To find the symmetric difference of two std::maps, we can use the std::set_symmetric_difference() function from the <algorithm> library. This function constructs a sorted range beginning at d_first consisting of elements that are found in either of the sorted ranges [first1, last1) and [first2, last2).

Syntax of set_symetric_difference()

set_symmetric_difference (first1,last1, first2, last2, result);

where,



C++ Program to Find the Symmetric Difference of Two Maps




// C++ Program to find the symmetric difference of two maps
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
  
int main()
{
    // Creating two maps of string and int
    map<string, int> map1 = { { "apple", 1 },
                              { "banana", 2 },
                              { "cherry", 3 } };
    map<string, int> map2 = { { "banana", 2 },
                              { "cherry", 3 },
                              { "date", 4 } };
  
    // Declaring a vector to store the symmetric difference
    vector<pair<string, int> > sym_diff;
  
    // Finding the symmetric difference of the two maps
    set_symmetric_difference(map1.begin(), map1.end(),
                             map2.begin(), map2.end(),
                             back_inserter(sym_diff));
  
    // Displaying the symmetric difference of the two maps
    for (auto it = sym_diff.begin(); it != sym_diff.end();
         ++it) {
        cout << it->first << " " << it->second << endl;
    }
  
    return 0;
}

Output
apple 1
date 4

Time Complexity: O(N + M), where N and M are the sizes of the two input maps.
Auxiliary Space: O(N + M)


Article Tags :