unordered_map clear in C++ STL
Last Updated :
18 Dec, 2018
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 = { };
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_map< int , int > ump1, ump2;
ump1[1] = 2;
ump1[3] = 4;
ump1[5] = 6;
ump1[7] = 8;
cout << "Unordered_map size before calling clear function: \n" ;
cout << "ump1 size = " << ump1.size() << endl;
cout << "ump2 size = " << ump2.size() << endl;
ump1.clear();
ump2.clear();
cout << "Unordered_map size after calling clear function: \n" ;
cout << "ump1 size = " << ump1.size() << endl;
cout << "ump2 size = " << ump2.size() << endl;
return 0;
}
|
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...