How to Find the Intersection of Two Maps in C++?
Last Updated :
28 Feb, 2024
In C++, a map is a container that stores elements in the form of key and value pairs. Intersection means the elements that are common between two datasets. In this article, we will learn how to find the intersection of two maps in C++ STL.
Example:
Input:
map1 = {{“apple”, 1}, {“banana”, 2}, {“cherry”, 3}};
map2 = {{“banana”, 2}, {“cherry”, 3}, {“date”, 4}};
Output:
Intersection= {{“banana”, 2}, {“cherry”, 3}}
Finding the Intersection of Two Maps in C++
There is no direct function to find the intersection of two maps in C++. But we can create a custom function that compares the key and values of pairs of two maps and if they match, it stores them to another map. It keeps doing this till all the elements of both the maps are scanned.
Approach
- Create a template function that takes two maps as input and returns a new map which is the intersection of the input maps.
- Inside this function, create an empty map that will store the intersection.
- Start by iterating the elements of the first map.
- For each key-value pair, check if the key exists in the second map.
- If the key exists in both maps, compare the value.
- If the value is same, add this pair to the intersection map.
- Keep doing that till all the elements of first map is scanned.
C++ Program to Find the Intersection of Two Maps
C++
#include <iostream>
#include <map>
using namespace std;
template < typename K, typename V>
map<K, V> find_intersection( const map<K, V>& map1,
const map<K, V>& map2)
{
map<K, V> intersection;
for ( const auto & pair : map1) {
K key = pair.first;
V value = pair.second;
if (map2.count(key) > 0) {
intersection[key] = value;
}
}
return intersection;
}
int main()
{
map< int , string> map1 = { { 1, "apple" },
{ 2, "banana" },
{ 3, "cherry" } };
map< int , string> map2 = { { 2, "banana" },
{ 4, "grape" },
{ 3, "orange" } };
map< int , string> intersection
= find_intersection(map1, map2);
for ( const auto & pair : intersection) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
|
Output
2: banana
3: cherry
Time Complexity: O(N), where N is the number of elements of the first map.
Auxiliary Space: O(K) where K is the number of elements in the intersection vector.
Share your thoughts in the comments
Please Login to comment...