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




C++ - REMOVE FROM MAP


How to remove an element from the Map?


Let us say, we have a Map that contains,

5, Is a Number

John, Is a Name

C++, Is a Language

As Key and Value pair.


Now, if you want to remove the entries from a Map, erase() and clear() Method can be used.


Let us look at the erase() Method first.


How to remove an element using the erase() Method?


The erase() Method can be used to remove an item from the Map.


Let us say, we want to remove the entry where the Key is Five and Value is Is a Number.

Five, Is a Number

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"}
        };
        
    x.erase("Five");
        
    for (auto i : x)  
    {  
        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 : John and the Value is :Is a Name

So, in the above code we have created a Map using braces {} and Key and Value pairs.


map<string, string> x =
	{
		{ "Five", "Is a Number" },
		{ "John", "Is a Name" },
		{ "C++", "Is a Language"}
	};

And initialised to the variable x.

java_Collections

Now, we are supposed to delete the value of the Key, Five.


So, we have used the below way to update it.


x.Remove("Five");

And the entry for the Key Five is deleted for the Map.

java_Collections

And we get the below output,

Output :



  The key is : John and the value is : Is a Name
  The key is : C++ and the value is : Is a Language

How to remove all the elements from the Map using clear() Method?


The clear() Method can be used to remove all the elements from the Map.


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"}
        };
        
    x.clear();
        
    for (auto i : x)  
    {  
        cout << "The Key is : " << i.first << " and the Value is :"  << i.second << endl;  
    }
    
    return 0;    
}


Output :




So, in the above code we have created a Map using braces {} and Key and Value pairs.


map<string, string> x =
	{
		{ "Five", "Is a Number" },
		{ "John", "Is a Name" },
		{ "C++", "Is a Language"}
	};

And initialised to the variable x.

java_Collections

And we have used the clear() method to remove all the elements from the Map.


x.clear()

And the print statement, prints an empty Map.