C++ Map Contains() Function | C++20 Tutorial

This tutorial will discuss how to C++ map contains() function | C++20 tutorial.

To check if a map contains a key or not in C++, we can use the contains() member function of map. An important point to note here is that this contains() function was introduced in C++20 only. Prior to that, we could use either the find() function or count() function to check if a map contains a key or not. But from C++20 onwards, we can directly use the contains() function.

The contains() function accepts a key as an argument and returns true if the calling map object has the given key, whereas it returns false if the calling map object does not have the key.

Suppose we have a map of string and integer.

std::map<std::string, int> wordFrequency{
                                    {"this", 22},
                                    {"why", 33},
                                    {"what", 67},
                                    {"how", 41} };

The keys are of string type and values are of integer type, basically it contains the frequency of each word in a text. Now we want to check if this map contains a particular key or not. For that, we can directly call the contains() function on the map and pass the key as an argument in it like this.

// Check if map contains a value or not
if (wordFrequency.contains("why"))
{
    std::cout << "Map Contains the key 'why'" << std::endl;
}
else
{
    std::cout << "Map does not Contains the key 'why'" << std::endl;
}

Output:

Map Contains the key 'why'

If returned true, because means the map contains the key ‘why’.

Let’s see the complete example,

#include <iostream>
#include <map>

int main()
{
    std::map<std::string, int> wordFrequency{
                                        {"this", 22},
                                        {"why", 33},
                                        {"what", 67},
                                        {"how", 41} };

    // Check if map contains a value or not
    if (wordFrequency.contains("why"))
    {
        std::cout << "Map Contains the key 'why'" << std::endl;
    }
    else
    {
        std::cout << "Map does not Contains the key 'why'" << std::endl;
    }

    // Check if map contains a value or not
    if (wordFrequency.contains("because"))
    {
        std::cout << "Map Contains the key 'because'" << std::endl;
    }
    else
    {
        std::cout << "Map does not Contains the key 'because'" << std::endl;
    }
    return 0;
}

Output

Map Contains the key 'why'
Map does not Contains the key 'because'

Summary

Today, we learned how to C++ map contains() function | C++20 tutorial.

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