Skip to content
Related Articles

Related Articles

map::clear() in C++ STL

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 20 Jan, 2018
View Discussion
Improve Article
Save Article


Map is dictionary like data structure. It is an associative array of (key, value) pair, where only single value is associated with each unique key.

map::clear()
clear() function is used to remove all the elements from the map container and thus leaving it’s size 0.

Syntax:

map1.clear()
where map1 is the name of the map.

Parameters:
No parameters are passed.

Return Value: None

Examples:

Input : map1 = { 
                {1, "India"},
                {2, "Nepal"},
                {3, "Sri Lanka"},
                {4, "Myanmar"}
               }
        map1.clear();
Output: map1 = {}

Input : map2 = {}
        map2.clear();
Output: map2 = {}




// CPP program to illustrate
// Implementation of clear() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Take any two maps
    map<int, string> map1, map2;
      
    // Inserting values
    map1[1] = "India";
    map1[2] = "Nepal";
    map1[3] = "Sri Lanka";
    map1[4] = "Myanmar";
      
    // Print the size of map
    cout<< "Map size before running function: \n";
    cout << "map1 size = " << map1.size() << endl;
    cout << "map2 size = " << map2.size() << endl;;
      
    // Deleting the map elements
    map1.clear();
    map2.clear();
      
    // Print the size of map
    cout<< "Map size after running function: \n";
    cout << "map1 size = " << map1.size() << endl;
    cout << "map2 size = " << map2.size();
    return 0;
}

Output:

Map size before running function: 
map1 size = 4
map2 size = 0
Map size after running function: 
map1 size = 0
map2 size = 0

Time complexity: Linear i.e. O(n)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!