This is the 4th Part of Tutorial Series on std::map in C++. In this tutorial, we will discuss how to access key-value Pairs in map.

A map is a binary search tree-based container allowing for ordered storage and retrieval of values based on their keys. There are several ways to access elements in a map. Let’s discuss them one by one.

Using the [] Operator:

The [] operator in C++’s map serves a dual purpose: it not only allows for the insertion of new elements but also provides a straightforward means to access existing ones. For example, when you use wordFrequency[“Why”] = 1;, the operator first checks if the key “Why” exists in the map named wordFrequency. If it doesn’t, a new element with this key and a value of 1 is added to the map. Conversely, if the key exists, its corresponding value is updated to 1.

Additionally, you can use the [] operator to access the value of an existing key, as seen with int frequency = wordFrequency[“Why”];, which retrieves the refernce to the value associated with key “Why”.

Let’s see an example,

#include <iostream>
#include <map>
#include <string>

int main() 
{
    std::map<std::string, int> wordFrequency = {
                                        {"How", 3},
                                        {"That", 4},
                                        {"Why", 8}};

    // Accessing the element
    int frequency = wordFrequency["Why"];  

    // Print the frequency
    std::cout << "Frequency of 'Why' is : " << frequency << std::endl;

    return 0;
}

Output:

Frequency of 'Why' is : 8

Note: The [] operator can inadvertently insert elements into the map if the key does not exist. Be cautious when using this in a const context or when you do not intend to modify the map.

Using the at() Method:

The map also offers the at() method. Unlike the [] operator, at() throws a std::out_of_range exception if the key does not exist in the map. However, if the key exists in the map, it returns a reference to the value associated with the key.

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map<std::string, int> wordFrequency = {
                                        {"How", 3},
                                        {"That", 4},
                                        {"Why", 8}};

    try
    {
        // Accessing the element
        int frequency = wordFrequency.at("Where");
        std::cout << "Frequency of 'Where' is : " << frequency << std::endl;
    }
    catch (const std::out_of_range &err)
    {
        std::cout << "Key not found. During " << err.what() << 'n';
    }

    return 0;
}

Output:

Key not found. During map::at

Like in this example, the key “Where” does not exist in the map, so the at() function threw the out_of_range error, and we caught that in the catch block.

By Iterating Over the Map

You can also use iterators to access all elements in the map. For that, we can loop over all key-value pairs in the map and print each key-value pair one by one. Let’s see the complete example:

#include <iostream>
#include <map>
#include <string>

int main() 
{
    std::map<std::string, int> wordFrequency = {
                                          {"Where", 20}, 
                                          {"How",    21}, 
                                          {"That",   19}
                                       };

    for (const auto& pair : wordFrequency) 
    {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}

Output:

How: 21
That: 19
Where: 20

Using the find() Method

The find() method in a map is an efficient way to search for a specific key within the map. It accepts a key as an argument and returns an iterator pointing to that key in the map. If the key does not exist in the map, then it returns an iterator pointing to the element next to the end of the map, i.e., an iterator returned by end(). Let’s see an example where we will look for a key-value pair where the key is “How”:

#include <iostream>
#include <map>
#include <string>

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map<std::string, int> wordFrequency = {
                                    {"Where", 20},
                                    {"How", 21},
                                    {"That", 19}};

    // Look for key 'How'
    auto it = wordFrequency.find("How");

    // Check if Iterator is valid
    if (it != wordFrequency.end())
    {
        // Key found
        int frequency = it->second;
        std::cout << "Key Found & Value is : " << frequency << 'n';
    }
    else
    {
        std::cout << "Key Not Found" << 'n';
    }

    return 0;
}

Output:

Key Found & Value is : 21

Summary

Today, we learned different ways to access the key-value pairs in a map in C++.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

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