unordered_map clear in C++ STL

unordered_map::clear() function is used to remove all elements from the container. When this function is applied to unordered_map its size becomes zero.
Syntax:

 unordered_map_name.clear()

Parameters: This function does not accepts any parameter
Return type: This function return nothing.

Examples:



Input: ump = { {1, 2}, {3, 4}, {5, 6}, {7, 8}}
ump.clear();
Output: ump = { };

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate
// Implementation of unordered_map clear() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Take any two unordered_map
    unordered_map<int, int> ump1, ump2;
  
    // Inserting values
    ump1[1] = 2;
    ump1[3] = 4;
    ump1[5] = 6;
    ump1[7] = 8;
  
    // Print the size of container
    cout << "Unordered_map size before calling clear function: \n";
    cout << "ump1 size = " << ump1.size() << endl;
    cout << "ump2 size = " << ump2.size() << endl;
  
    // Deleting the  elements
    ump1.clear();
    ump2.clear();
  
    // Print the size of container
    cout << "Unordered_map size after calling clear function: \n";
    cout << "ump1 size = " << ump1.size() << endl;
    cout << "ump2 size = " << ump2.size() << endl;
  
    return 0;
}

chevron_right


Output:

Unordered_map size before calling clear function: 
ump1 size = 4
ump2 size = 0
Unordered_map size after calling clear function: 
ump1 size = 0
ump2 size = 0

What is the application?
clear is used when we wish to delete old elements and start from fresh, especially in loops. We can achieve same functionality by creating a new map, but clearing same map is better performance wise as we do not have to create new object.



My Personal Notes arrow_drop_up

All powers are within you You can do anything and everything Believe in that

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.