C++ Standard Library C++ STL Library

C++ unordered_map - clear() Function



The C++ unordered_map::clear function is used to clear all elements of the unordered_map. This function makes the unordered_map empty with a size of zero.

Syntax

void clear() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n)

Example:

In the example below, the unordered_map::clear function is used to clear all elements of the unordered_map called uMap.

#include <iostream>
#include <unordered_map>
using namespace std;
 
int main (){
  unordered_map<int, string> uMap;
  unordered_map<int, string>::iterator it;

  uMap[101] = "John";
  uMap[102] = "Marry";
  uMap[103] = "Kim";
  uMap[104] = "Jo";
  uMap[105] = "Ramesh";

  cout<<"Before clear() function: \nThe unordered_map contains:\n";
  for(it = uMap.begin(); it != uMap.end(); ++it)
    cout<<it->first<<" "<<it->second<<"\n";
  cout<<"\nUnordered Map size is: "<<uMap.size()<<"\n\n";

  uMap.clear();

  cout<<"After clear() function: \nThe unordered_map contains:\n";
  for(it = uMap.begin(); it != uMap.end(); ++it)
    cout<<it->first<<" "<<it->second<<"\n";
  cout<<"Unordered Map size is: "<<uMap.size();
  return 0;
}

The output of the above code will be:

Before clear() function: 
The unordered_map contains:
105 Ramesh
104 Jo
103 Kim
101 John
102 Marry

Unordered Map size is: 5

After clear() function: 
The unordered_map contains:
Unordered Map size is: 0

❮ C++ <unordered_map> Library