How to merge two maps in C++

In this tutorial, we will discuss How to merge two maps in C++ easily. So before implementing let’s understand the approach that we are going to use.

1) Header file:- The first step is to include a header file map.

#include <map>

2) Map Creation:- Now we will create two maps (i.e. map1 and map2) in which both the keys and values are of data-type int.

map<int, int> map1 = { {1, 10}, {2, 20} };
map<int, int> map2 = { {3, 30}, {4, 40} };

3) Using insert function:- In order to merge two maps, we will use the built-in function insert. It will insert map2 in map1 from beginning till end. let’s see how to do it.

map1.insert(map2.begin(), map2.end());

4) Printing the merged Map:- The Final step is to print the map using for loop. Here using .first we can access the key similarly .second help us to access the value corresponding to the key.

for (auto  &i: map1) {
cout << i.first <<" "<< i.second << endl;
}

 

Entire C++ code to merge two maps

#include <iostream>
#include <map>
using namespace std;

int main()
{
    map<int, int> map1 = { {1, 10}, {2, 20} };
    map<int, int> map2 = { {3, 30}, {4, 40} };

    map1.insert(map2.begin(), map2.end());

    cout<<"KEY & VALUE"<<endl;

    for (auto  &i: map1) {
        cout << i.first <<" "<< i.second << endl;
    }


    return 0;
}




 

Output:-

KEY & VALUE
1 10
2 20
3 30
4 40

Also read: Map lower_bound() function in C++ STL

Leave a Reply

Your email address will not be published.