unordered_map clear in C++ STL (original) (raw)

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

CPP `

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

}

`

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.