Javatpoint Logo
Javatpoint Logo

C++ map erase() function

C++ map erase() function is used to remove either a single element associated with a given key value or a range of elements from the map container. Hence, the size will be reduced by the number of elements removed.

Syntax

Parameter

position: An iterator pointing to a single element to be removed from the map.

k: Key of the element to be removed from the map.

first: beginning of the range to erase.

last: End of the range to erase.

Return value

It returns an iterator that points to the next element of the deleted element or returns the number of deleted elements.

Example 1

Let's see a simple example to erase the element by the iterator.

Output:

Before erasing the element: 
a => 10
b => 20
c => 30
d => 40

After erasing the element: 
a => 10
c => 30
d => 40

In the above example, element is erased by the iterator it.

Example 2

Let's see a simple example to erase the element of the map with the given key value.

Output:

Before erasing the element: 
a => 10
b => 20
c => 30
d => 40

After erasing the element: 
a => 10
b => 20
d => 40

In the above example, erase(key) function uses the key value 'c' and its value from the map.

Example 3

Let's see a simple example to erase the element by the given range.

Output:

Before erasing the element are: 
Size is: 4
a => 10
b => 20
c => 30
d => 40

After erasing the element are: 
Size is: 0

In the above example, erase(first, last) function is used to erase the element with the given range i.e begin to end.

Example 4

Let's see a simple example to erase all the odd numbers from the map.

Output:

After erasing odd numbers,elements are:
 
two, four, six,

In the above example, all the odd numbers have been erased and displaying even numbers.

Next TopicC++ Map



Help Others, Please Share

facebook twitter pinterest