C++ Standard Library C++ STL Library

C++ multimap - clear() Function



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

Syntax

void clear();
void clear() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n)

Example:

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

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  multimap<string, string> MyMMap;
  multimap<string, string>::iterator it;

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

  cout<<"Before clear() function: \nMyMMap contains:\n";
  for(it = MyMMap.begin(); it != MyMMap.end(); ++it)
    cout<<it->first<<" "<<it->second<<"\n";
  cout<<"\nMyMMap size is: "<<MyMMap.size()<<"\n\n";

  MyMMap.clear();

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

The output of the above code will be:

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

MyMMap size is: 5

After clear() function: 
MyMMap contains:
MyMMap size is: 0

❮ C++ <map> Library