Copy a map in C++
This post will discuss how to copy a map in C++.
1. Using copy constructor
We can use a copy constructor to initialize a map from elements of another map. We can also use operator= to copy a map, that is functionally the same as above. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> #include <map> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'} }; std::map<int, char> map_copy(map); // or // std::map<int, char> map_copy = map; for (const auto &entry: map_copy) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
Output:
{1, A}
{2, B}
{3, C}
2. Using std::map::insert
Another option is to use the std::map::insert function that extends the map container by inserting the elements from the specified range, as shown below. This function can be used if the map already contains some key-value pairs.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <map> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'} }; std::map<int, char> map_copy; map_copy.insert(map.begin(), map.end()); for (const auto &entry: map_copy) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
Output:
{1, A}
{2, B}
{3, C}
3. Using std::copy
Finally, we can use the std::copy standard algorithm with an insert iterator to copy the contents of the original map to another map. The following solution demonstrates this using std::inserter, defined in header <iterator>:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <map> #include <iterator> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'} }; std::map<int, char> map_copy; std::copy(map.begin(), map.end(), std::inserter(map_copy, map_copy.end())); for (const auto &entry: map_copy) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
Output:
{1, A}
{2, B}
{3, C}
That’s all about copying a map 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 :)