It is quite simple to make a copy of the Map and assign it to other variable.
There are two ways to do it.
Let us look at the first way :
#include <iostream> #include <map> using namespace std; int main() { map<string, string> x = { { "Five", "Is a Number" }, { "John", "Is a Name" }, { "C++", "Is a Language"} }; map<string, string> y(x); for (auto i : y) { cout << "The Key is : " << i.first << " and the Value is :" << i.second << endl; } return 0; }
So, in the above code we have created a Map and initialised to the variable x.
map<string, string> x = { { "Five", "Is a Number" }, { "John", "Is a Name" }, { "C++", "Is a Language"} };
Then we have created another Map y and passed the above Map x as Parameter.
map<string, string> y(x);
And if we see the below output,
The key is : Five and the value is : Is a Number The key is : John and the value is : Is a Name The key is : C++ and the value is : Is a Language
The new variable y is an exact copy of x.
Now, let us look at the second way.
#include <iostream> #include <map> using namespace std; int main() { map<string, string> x = { { "Five", "Is a Number" }, { "John", "Is a Name" }, { "C++", "Is a Language"} }; map<string, string> y = x; for (auto i : y) { cout << "The Key is : " << i.first << " and the Value is :" << i.second << endl; } return 0; }
So, in the above code, we have used the second way to copy a Map to another.
We have created a Map named x,
map<string, string> x = { { "Five", "Is a Number" }, { "John", "Is a Name" }, { "C++", "Is a Language"} };
Then we have used the = operator to copy the Map to another Map y.
map<string, string> y = x;