What is the unordered_map::clear() function in C++?

Overview

In this shot, we’ll learn how to use the unordered_map::clear() function.

Introduction

The unordered_map::clear() function is available in the <unordered_map> header file in C++.

The unordered_map::clear() removes all the elements from the unordered map. In other words, it empties the unordered map.

Syntax

The syntax of the unordered_map::clear() function is given below.

void clear();

Parameter

The unordered_map::clear() function does not accept any parameters.

Return value

The unordered_map::clear() does not return any value.

Code

Let’s take a look at the code.

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int,string> umap ={
{12, "unordered"},
{16, "map"},
{89, "in"},
{66, "C++"}
};
cout << "Original Map:\n";
cout << "Size of the Map: " << umap.size() << endl;
for(auto m: umap)
cout << m.first << " -> " << m.second << endl;
umap.clear();
cout << "Original Map:\n";
cout << "Size of the Map: " << umap.size() << endl;
for(auto m: umap)
cout << m.first << " -> " << m.second << endl;
return 0;
}

Explanation

  • Lines 1–2: We import the required header files.

  • Line 5: We made a main() function.

  • Lines 7 to 12: We initialize an unordered map with integer type keys and string type values.

  • Line 15: We print the current size of the map.

  • Lines 16 to 17: We print all the key-value pairs present in the map.

  • Line 19: We call the unordered_map::clear() function to empty the map.

  • Line 21: We again print the size of the map. Now, we can see that the size is 00.

  • Lines 22–23: We try to print the map again, but this loop will not execute since the map is empty.

Free Resources