Remove element from the map container in C++

Hello guys, In this tutorial, we will learn how to remove an element from the map container in C++.

Suppose we want to store the name and roll number of each student, then the map will look like below:

<4,Ram>
<6,Shyam>
<10,faiz>
<16,Harpreet>
<12,Shivam>

Creating map

map<data_type1,data_type2> map_name;

Inserting in map

We use built-in insert() function to insert an element in map.

map_name.insert({key,value});
#include <iostream>
#include<map>
using namespace std;
int main() {
  map<int,string> mp;   //declaring map
  
  mp.insert({1,"INDIA"});    //inserting in map 
  mp.insert({2,"CHINA"});    //inserting in map 
  mp.insert({3,"USA"});      //inserting in map 
  mp.insert({4,"RUSSIA"});   //inserting in map 
  
  for(auto i=mp.begin();i!=mp.end();i++)
  {  
     
    cout << i->first <<" "<<i->second<<endl;    //i->first will print key.
                                                //i->second will print value.
      
  }
  
  return 0;
}

Output

1 INDIA
2 CHINA
3 USA
4 RUSSIA

C++ program to remove element from the map container

erase(key)- It will delete a key and its value. The return type of this function is an integer. It returns how many entries deleted.

#include <iostream>
#include<map>
using namespace std;
int main() {
  map<int,string> mp;   //declaring map
  
  mp.insert({1,"INDIA"});    //inserting in map 
  mp.insert({2,"CHINA"});    //inserting in map 
  mp.insert({3,"USA"});      //inserting in map 
  mp.insert({4,"RUSSIA"});   //inserting in map 
  
  for(auto i=mp.begin();i!=mp.end();i++)
  {  
     
    cout << i->first <<" "<<i->second<<endl;    //i->first will print key.
                                                //i->second will print value.
      
  }
  
  
  
  int x=mp.erase(2);   //calling erase fuction  and deleting key 2
  
  for(auto i=mp.begin();i!=mp.end();i++)
  {  
     
    cout << i->first <<" "<<i->second<<endl;    //i->first will print key.
                                                //i->second will print value.
  }
  
  return 0;

}
1 INDIA
2 CHINA
3 USA
4 RUSSIA
1 INDIA
3 USA
4 RUSSIA

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *