In this article we will discuss the different ways to delete a key-value pair from map.

std::map provides 3 overloaded version of erase() to remove elements from map i.e.

  • Erase by key
  • Erase by Iterator
  • Erase a range

Lets discuss them one by one,

Erase Element from Map by Key

std::map provides a erase function that accepts the key and removes the elements (Key- Value pairs) whose key matches the passed key k.

It returns the number of elements deleted, but as there can be unique keys only in std::map. Therefore it will return 1 if element is deleted else it will return 0 if given key is not found in map.

Suppose we have a map of word and int i.e.

Now, lets delete the element with key “is” i.e.

Checkout Complete example as follows,

Output:

Erase Element from Map by Iterator

std::map provides a erase function that accepts the Iterator and removes the element pointed by the iterator.

It returns the iterator of the next element.

Suppose we have a map of word and int i.e.

Now, lets delete the element with key “of” i.e.

Let’s first find the iterator pointing to it i.e.

Then check if iterator is valid or not. If its valid then only remove the element through it

Checkout Complete example as follows,

Output:

Erase Element from Map by Iterator Range

std::map provides a erase function that accepts the Iterator start and end and removes all the elements in the given range i.e. from start to end -1 i.e.

Suppose we have a map of word and int i.e.

Now, lets delete the elements in range of two iterator it1 & it2 i.e.

It will delete the elements from it1 to it2 -1.

Checkout Complete example as follows,

Output:

 

 

 

 

Click Here to Subscribe for more Articles / Tutorials like this.