Home »
C++ STL
unordered_map clear() Function in C++ with Examples
C++ unordered_map clear() Function: Here, we will learn about the clear() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on July 20, 2022
An unordered_map is a special type of container that stores data in the form of key-value pairs in an unordered manner. The key stored is used to identify the data value mapped to it uniquely.
C++ STL std::unordered_map::clear() Function
The clear() function is used to remove all elements present in the unordered_map and resize it to 0. This method empties the unordered_map to be reused again.
Syntax
unordered_mapName.clear();
Parameter(s)
It does not require any parameter to perform its task.
Return value
It returns nothing, just empties the unordered_map.
Note: The clear() function is used when the program requires an empty structure with the same specification and the current values are not required. This improves performance as new allocation is not done.
Example
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int, char> myUnorderedMap = { { 1, 'a' }, { 5, 'x' }, { 9, 's' } };
cout << "Size of unordered_map " << myUnorderedMap.size() << endl;
cout << "The elements of unordered_map are ";
for (auto x : myUnorderedMap)
cout << x.first << " : " << x.second << "\t";
cout << endl;
myUnorderedMap.clear();
cout << "After using clear() method.\n";
cout << "Size of unordered_map " << myUnorderedMap.size() << endl;
cout << "The elements of unordered_map are ";
for (auto x : myUnorderedMap)
cout << x.first << " : " << x.second << "\t";
cout << endl;
return 0;
}
Output
Size of unordered_map 3
The elements of unordered_map are 9 : s 5 : x 1 : a
After using clear() method.
Size of unordered_map 0
The elements of unordered_map are