C++ Standard Library C++ STL Library

C++ unordered_multimap - clear() Function



The C++ unordered_multimap::clear function is used to clear all elements of the unordered_multimap. This function makes the unordered_multimap 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_multimap::clear function is used to clear all elements of the unordered_multimap called uMMap.

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

  uMMap.insert(pair<string, string>("USA", "New York"));
  uMMap.insert(pair<string, string>("USA", "Washington"));  
  uMMap.insert(pair<string, string>("CAN", "Toronto"));
  uMMap.insert(pair<string, string>("CAN", "Montreal"));
  uMMap.insert(pair<string, string>("IND", "Delhi"));

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

  uMMap.clear();

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

The output of the above code will be:

Before clear() function: 
The unordered_multimap contains:
IND Delhi
CAN Montreal
CAN Toronto
USA Washington
USA New York

Unordered Multimap size is: 5

After clear() function: 
The unordered_multimap contains:
Unordered Multimap size is: 0

❮ C++ <unordered_map> Library