Check if a Map is Empty in C++

This tutorial will discuss how to check if a map is empty in C++.

To check if a map is empty or not, we can use the member function empty() from std::map in C++. The map class provides a function, empty(), which returns true if the calling map object does not have any key-value pair in it.

So, we can directly use this function to check if a map is empty or not. Let us see an example, where we will create a map of string and integer, where keys will be of string type and values will be of integer type.

std::map<std::string, int> wordFrequency;

While creating the map object, we will not initialize it with any key-value pair. This means there will be no size of the map, it will be zero. Then, we can call the empty() function on the map object to check if the calling map object has any key-value pair or not.

if (wordFrequency.empty())
{
    std::cout << "Map is empty." << std::endl;
}
else
{
    std::cout << "Map is not empty." << std::endl;
}

In this case, its size will be zero so the empty() function will return true.

Let’s see the complete example,

#include <iostream>
#include <map>

int main()
{
    std::map<std::string, int> wordFrequency;

    // Check if the map is empty
    if (wordFrequency.empty())
    {
        std::cout << "Map is empty." << std::endl;
    }
    else
    {
        std::cout << "Map is not empty." << std::endl;
    }

    return 0;
}

Output

Map is empty.

Summary

Today, we learned how to check if a map is empty in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top