Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C++ - COPY FROM MAP


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 :


Example :



#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;    
}


Output :



  The Key is : C++ and the Value is :Is a Language
  The Key is : Five and the Value is :Is a Number
  The Key is : John and the Value is :Is a Name

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);
java_Collections


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.


Example :



#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;    
}


Output :



  The Key is : C++ and the Value is :Is a Language
  The Key is : Five and the Value is :Is a Number
  The Key is : John and the Value is :Is a Name

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;