map::clear() in C++ STL


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 = {}

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.