C++ Standard Library C++ STL Library

C++ map - empty() Function



The C++ map::empty function is used to check whether the map is empty or not. It returns true if the size of the map is zero, else returns false.

Syntax

bool empty() const;
bool empty() const noexcept;

Parameters

No parameter is required.

Return Value

true if the size of the map is zero, else returns false.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the map::empty function is used to check whether the map is empty or not.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<int, string> MyMap;

  cout<<boolalpha;

  cout<<"Is the Map empty?: "<<MyMap.empty()<<"\n";

  cout<<"Add key/element pairs in the Map:\n";

  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";

  cout<<"Now, Is the Map empty?: "<<MyMap.empty()<<"\n";
  return 0;
}

The output of the above code will be:

Is the Map empty?: true
Add key/element pairs in the Map:
Now, Is the Map empty?: false

❮ C++ <map> Library