In C++, finding the intersection of two multimaps consists of identifying the common elements that are shared between both collections, containing key-value pairs. In this article, we will learn how to find the intersection of two multimaps in C++ STL.
Example:
Input:
multimap1 = {1, "Java"}, {2, "Python"}, {3, "C++"}, {4, "JavaScript"}
mutlimap2 = {2, "Python"}, {4, "JavaScript"}, {5, "TypeScript"}
Output:
Intersection:
{2: Python}
{4: JavaScript}
Intersection of Two Multimaps With Common Values in C++
To find the intersection between two multimaps in C++ STL, we have to iterate through each element using a loop in the first multimap and search for the corresponding elements in the second multimap. If the matching element is found then it is inserted into the result multimap.
C++ Program to Find the Intersection of Two Multimaps
The below program demonstrates how we can find the intersection between two multimaps in C++.
// C++ Program to illustrate how to find the intersection 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 Intersection between multimap1 and multimap2
multimap< int , string> res;
for ( const auto & pair : multi1) {
auto range = multi2.equal_range(pair.first);
for ( auto it = range.first; it != range.second;
++it) {
if (it->second == pair.second) {
res.insert(*it);
break ;
}
}
}
// Printing intersection result
cout << "Intersection MultiMap:" << endl;
for ( const auto & pair : res) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
} |
Intersection MultiMap: 2: Python 4: JavaScript
Time Complexity: O(min(N, M), where N is the number of elements in multi1 and M is the number of elements in multi2.
Auxilliary Space: O(K), where K is the number of common elements.