Open In App

How to Merge Two STL Maps in C++?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, maps are associative containers provided by the STL library that store the elements in key-value p,irs and concatenating two maps means merging two maps while ensuring that duplicate keys are handled appropriately. In this article, we will learn how to concatenate two maps in C++.

Example

Input:
map1= {{10, "A"}, {20,"B"}}
map2= {{30,"C"}, {40,"D"}}

Output:
Map1 after Concatenation= {{10,"A"}, {20,"B"}, {30,"C"}, {40,"D"}}

Merge Two STL Maps in C++

To concatenate two std::maps in C++, we can use the std::map::insert() function that is used to insert a range of key-value pairs into the map. We can pass the iterators to the start and end of the second map and this function will insert all the elements of the second map to the first map without duplication.

C++ Program to Concatenate Two Maps

The below example demonstrates how we can concatenate two maps using the std::insert() function in C++.

C++




// C++ Program to illustrate how to concatenate two maps in
// C++
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Intializing two maps
    map<int, string> map1{ { 10, "Mike" }, { 20, "John" } };
    map<int, string> map2{ { 30, "Alice" }, { 40, "Bob" } };
  
    // Concatenate both the maps
    map1.insert(map2.begin(), map2.end());
  
    // Print the concatenated map
    cout << "Concatenated Map:{";
    for (auto pair : map1) {
        cout << "{" << pair.first << ": " << pair.second
             << "}";
    }
    cout << " }" << endl;
    return 0;
}


Output

Concatenated Map:{{10: Mike}{20: John}{30: Alice}{40: Bob} }

Time Complexity: O(M logN), here N is the number of elements in the first map and M is the elements in the second map.
Auxiliary Space: O(M)

Note: To concatenate two maps in C++ both the maps should be of same type.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads