Merge two maps in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> int main() { std::map<int, char> first = { {1, 'A'}, {2, 'B'} }; std::map<int, char> second = { {3, 'C'}, {4, 'D'} }; first.insert(second.begin(), second.end()); for (auto const &entry: first) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> int main() { std::map<int, char> first = { {1, 'A'}, {2, 'B'} }; std::map<int, char> second = { {2, 'C'}, {4, 'D'} }; first.insert(second.begin(), second.end()); for (auto const &entry: first) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> int main() { std::map<int, char> first = { {1, 'A'}, {2, 'B'} }; std::map<int, char> second = { {2, 'C'}, {4, 'D'} }; first.merge(second); for (auto const &entry: first) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <map> int main() { std::map<int, char> first = { {1, 'A'}, {2, 'B'} }; std::map<int, char> second = { {2, 'C'}, {4, 'D'} }; for (auto &it: second) { first[it.first] = it.second; } for (auto const &entry: first) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
Output:
{1, A}
{2, C}
{4, D}
That’s all about merging two maps in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)