This post will discuss how to merge two maps in C++.

1. Using std::map::insert

In C++14 and before, the recommended approach to merge two maps is using the std::map::insert function. It accepts iterators pointing to the beginning and the end of another map whose elements need to be added to the original map. A typical invocation of this function would look like:

Download  Run Code

Output:

{1, A}
{2, B}
{3, C}
{4, D}

 
Note that if a key exists in both maps, the value in the specified map will not overwrite the value in the original map. For example,

Download  Run Code

Output:

{1, A}
{2, B}
{4, D}

2. Using std::map::merge

Since C++17, std::map provides std::map::merge member function, which can be used to merge two or more maps in C++. Here’s an example of its usage. If a key exists in both maps, the value in specified map will not overwrite the value in the original map. For example,

Download Code

Output:

{1, A}
{2, B}
{4, D}

3. Using Loop

Finally, we can write custom logic for copying elements from one map to another using a for loop. If a key exists in both maps, the value in the specified map will overwrite the value in the original map. For example,

Download  Run Code

Output:

{1, A}
{2, C}
{4, D}

That’s all about merging two maps in C++.