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

An unordered_map is a hash table-based container allowing for fast retrieval of values based on their keys. There are several ways to access elements in an unordered_map. Let’s discuss them one by one.

Using the [] Operator:

The [] operator in C++’s unordered_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 unordered_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 value associated with “Why”.

#include <iostream>
#include <unordered_map>
#include <string>

int main() 
{
    // Define an unordered_map to store word frequencies
    std::unordered_map<std::string, int> wordFrequency;

    // Inserting a new element
    wordFrequency["Why"] = 1;

    // 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 : 1

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:

To address the potential pitfalls of the [] operator, the unordered_map offers the at() method. This method is designed to provide a safer way to access elements, incorporating bounds checking to prevent accidental modifications to the map. Unlike the [] operator, at() throws a std::out_of_range exception if the key does not exist in the map.

#include <iostream>
#include <unordered_map>
#include <string>

int main() 
{
    // Define an unordered_map to store word frequencies
    std::unordered_map<std::string, int> wordFrequency;

    // Inserting a new element
    wordFrequency["Why"] = 1;

    try 
    {
        // Accessing the element
        int frequency = wordFrequency.at("Where");

        // Use frequency...
    } catch (const std::out_of_range& e) 
    {
        std::cout << "Key not found: " << e.what() << 'n';
    }

    return 0;
}

Output:

Key not found: _Map_base::at

In the code above we are trying to access a non-existent key “Where” using wordFrequency.at(“Where”). It will result in an exception, which is then caught and handled in the catch block. The at() method is particularly useful in scenarios where it’s essential to confirm the existence of a key before proceeding, thus avoiding the risk of adding unintended elements to the map.

Iterating Over the Map

You can use iterators to access all elements in the map. This method is useful when you need to process or inspect each element.

The example below, we will iterate over an unordered_map named wordFrequency using a range-based for loop:

#include <iostream>
#include <unordered_map>
#include <string>

int main() 
{
    std::unordered_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:

That: 19
How: 21
Where: 20

In this loop, pair is a reference to each key-value pair in the wordFrequency map. The pair.first refers to the key, and pair.second refers to the corresponding value. This method of iteration is efficient and concise, making it ideal for various operations like printing all elements, computing aggregates, or applying transformations.

Using the find() Method

The find() method in unordered_map is an efficient way to search for a specific key within the map. This method is important when you want to access or modify the value associated with a particular key, or to check if a key exists in the map. Here’s how the find() method is used:

#include <iostream>
#include <unordered_map>
#include <string>

int main() 
{
    std::unordered_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';
        // Key not found
    }

    return 0;
}

Output:

Key Found & value is: 21

In this example, wordFrequency.find(“How”) searches for the key “How” in the map. The method returns an iterator it to the found element. If the key is not found, the iterator equals wordFrequency.end(), which is a special iterator that denotes a position past the last element in the map. Checking if it is not equal to wordFrequency.end() allows you to determine if the key was found. If found, it->second gives you access to the value associated with the key. This approach is highly efficient, especially in cases where the map contains a large number of elements, as the underlying hash table of the unordered_map provides fast access to elements.

Summary

Today, we learned different ways to access the key-value pairs in an unordered_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.