Skip to content
Related Articles

Related Articles

Improve Article

map::clear() in C++ STL

  • Difficulty Level : Easy
  • Last Updated : 20 Jan, 2018

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.

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


where map1 is the name of the map.

No parameters are passed.

Return Value: None


Input : map1 = { 
                {1, "India"},
                {2, "Nepal"},
                {3, "Sri Lanka"},
                {4, "Myanmar"}
Output: map1 = {}

Input : map2 = {}
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
    // 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;


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)

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :