.empty()
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 objectmap<int, char> emptyMap;// Check if the map is empty using the .empty() function and store the resultbool isEmpty = emptyMap.empty();// Use the value stored in 'isEmpty' to display whether the map is empty or notisEmpty ? 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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours