How To Find the Difference of Two Multimaps in C++?

In C++ STL, finding the difference between two multimaps consists of identifying the elements that exist in one multimap but are not present in the other. In this article, we will learn how to find the difference between two multimaps in C++ STL.

Example:

Input:
multimap1 = {1, "Java"}, {2, "Python"}, {3, "C++"}, {4, "JavaScript"}
mutlimap2 = {2, "Python"}, {4, "JavaScript"}, {5, "TypeScript"}

Output: 
Multimap after difference:
1: Java
3: C++

Finding the Difference Between Two Multimaps in C++

To find the difference between two std::multimap in C++, we can use the std::multimap::equal_range and follow the given approach.

Approach:

  • Iterate through the elements of the first multimap (multimap1)
  • For each element in multimap1, check if the corresponding key exists in the second multimap (multimap2) using equal_range.
  • If the key is not found, then insert the element into a new multimap (diff),
  • Finally, print multimap diff which contains elements that are present in multi1 but not in multi2.

C++ Program to Find the Difference of Two Multimaps

The below program demonstrates how we can find the difference between two multimaps in C++ STL.

C++




// C++ Program to illustrate how to find the difference of
// two multimaps
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Defining multimap1
    multimap<int, string> multi1 = { { 1, "Java" },
                                     { 2, "Python" },
                                     { 3, "C++" },
                                     { 4, "JavaScript" } };
  
    // Defining multimap2
    multimap<int, string> multi2 = { { 2, "Python" },
                                     { 4, "JavaScript" },
                                     { 5, "TypeScript" } };
  
    // Finding difference between multimap1 and multimap2
    multimap<int, string> diff;
    for (const auto& pair : multi1) {
        auto range = multi2.equal_range(pair.first);
        if (range.first == range.second) {
            diff.insert(pair);
        }
    }
    // Printing difference
    cout << "Difference MultiMap:" << endl;
    for (const auto& pair : diff) {
        cout << pair.first << ": " << pair.second << endl;
    }
    return 0;
}


Output

Difference MultiMap:
1: Java
3: C++

Time Complexity: O(N * log M) where N is the number of elements in multi1 and M is the number of elements in multi2.
Auxiliary Space: O(N)