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

In this shot, we will learn how to use the unordered_map::empty() function in C++.

Introduction

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

The unordered_map::empty() is used to check whether the unordered map is empty or not.

Syntax

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

unordered_map<int,int> umap = {};
umap.empty();

Parameter

The unordered_map::empty() method does not accept any parameters.

Return value

The unordered_map::empty() returns a boolean value:

  • True: If the unordered map is empty, then a boolean value of true is returned.
  • False: If the unordered map is not empty, then a boolean value of false is returned.

Example

Let’s have a look at the code below:

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int,string> umap ={
{12, "unordered"},
{16, "map"},
{89, "in"},
{66, "C++"}
};
if(umap.empty())
cout<<"Unordered map is empty" << endl;
else
cout<<"Unordered map is not empty" << endl;
umap.clear();
if(umap.empty())
cout<<"Unordered map is empty";
else
cout<<"Unordered map is not empty";
return 0;
}

Explanation

  • In lines 1 and 2, we imported the required header files.

  • In line 5, we made a main() function.

  • From lines 7 to 12, we initialized an unordered map with integer type keys and string type values.

  • From lines 14 to 17, we checked whether the map is empty or not by calling the unordered_map::empty() function.

  • In line 19, we use the unordered_map::clear() function to clear or remove all the elements from the map.

  • Again, from lines 20 to 23, we check whether the map is empty or not. At this point, the map is empty.

So, in this way, we can easily check whether the map is empty or not using the unordered_map::empty() function in C++.

Free Resources