map::clear function

The map::clear function allows you to clear all the elements of the map.

void clear();

If you want to remove a specified number of elements use erase() function instead.

Link:map::erase function


Return type

After this function is called the number of elements is reduced to 0.The size becomes 0.

Code example

map<int,string> mp{{ 2 , “two”} , {23 ,”Twenty-three”} , {0 , “Zero”}};

cout<< mp.size( ) << endl ;

mp.clear( );

cout<< mp.size( ) << endl ;




Stop wasting time,earn money($$$) from your website-Join Now!

In using this function if the elements are a pointer than the storage pointed by the pointers in not deleted when clear() is called.It is the programmer’s responsibility to handle the storage pointed by the pointers.

Code example

int *i=new int(89) ,
i1=new int(123) ;

map<int*,string> mp1{{ i , “First” } , { i1 , “Second” }};

cout<< mp1[i] << ” ” << mp1[i1] << endl ;

mp1.clear( );

cout << *i << ” ” << *i1 << endl ;

delete i; //Do not forget!
delete i1; //Do not forget!


First Second
89 123

After clearing the map element we could still access the dynamic storage pointed by the ‘i’ and ‘i1’ pointers.This means the storage is still alive .Hence we called delete operators on them to delete the storage.

Link:new and delete operators