How to use clear() In C++
The clear function clears all the elements present in the map. After this function is called, the size of map becomes 0.
Syntax
map_name.clear()
Example
CPP
// C++ code to demonstrate the working of clear() #include <iostream> #include <map> // for map operations using namespace std; int main() { // declaring map // of char and int map< char , int > mp; // declaring iterator map< char , int >::iterator it; // inserting values mp[ 'a' ] = 5; mp[ 'b' ] = 10; mp[ 'c' ] = 15; mp[ 'd' ] = 20; mp[ 'e' ] = 30; // printing initial map elements cout << "The initial map elements are : \n" ; for ( auto it1 = mp.begin(); it1 != mp.end(); ++it1) cout << it1->first << "->" << it1->second << endl; // using clear() to erase all elements in map mp.clear(); // printing map elements after deletion cout << "The map elements after clearing all elements " "are : \n" ; for ( auto it1 = mp.begin(); it1 != mp.end(); ++it1) cout << it1->first << "->" << it1->second << endl; } |
Output
The initial map elements are : a->5 b->10 c->15 d->20 e->30 The map elements after clearing all elements are :
Different ways to delete elements in std::map (erase() and clear())
This article deals with the deletion part of Maps. We can delete elements in std::map using two functions