.empty()

brodes4JC7606490867's avatar
Published Nov 9, 2024
Contribute to Docs

In the C++ Standard Template Library (STL), the .empty() function is a member function under the std::map class that checks if an STL map object contains any key-value pairs. It returns true if the map is empty and false otherwise.

Syntax

myMap.empty();
  • myMap: The map to be checked.

Example

The following example calls the .empty() function, stores its return value in a boolean variable and uses this value to display whether the map is empty or not:

#include <map>
#include <cstdio>
using namespace std;
int main(){
// Create an empty STL map object
map<int, char> emptyMap;
// Check if the map is empty using the .empty() function and store the result
bool isEmpty = emptyMap.empty();
// Use the value stored in 'isEmpty' to display whether the map is empty or not
isEmpty ? printf("The map is empty.") : printf("The map is not empty.");
return 0;
}

The code above produces the following output:

The map is empty.

Codebyte Example

The following code creates two STL map objects with one left empty and the other initialized with elements. The .empty() function is then called on each map, returning a boolean indicating if the map is empty:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy