This is the 6th Part of Tutorial Series on unordered_map. In this tutorial, we will learn how to remove key-value pairs from unordered_map in C++.

Suppose we have an unordered_map like this,

std::unordered_map<std::string, int> wordFrequency = {
                                        {"Where", 20}, 
                                        {"Why",    21}, 
                                        {"That",   19}
                                    };

Now we will see how to remove certain key-value pairs from this unordered_map by its key.

Using the erase() function with a Key

The erase() function in C++’s unordered_map provides a way to remove elements based on their keys. Let’s see an example,

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

int main() 
{
    std::unordered_map<std::string, int> wordFrequency = {
                                            {"Where", 20}, 
                                            {"Why", 21}, 
                                            {"That", 19}
                                        };
    // Removes the element with key "Why"
    wordFrequency.erase("Why"); 

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

    return 0;
}

Output:

Key: That :: Value: 19
Key: Where :: Value: 20

In this example, wordFrequency.erase(“Why”) attempts to remove an element with the key “Why” from the wordFrequency map. If the key “Why” exists in the map, the corresponding element is removed. If the key does not exist, the map remains unchanged. The erase() method returns the number of elements removed, which can be either 1 (if the element was found and removed) or 0 (if the element was not found).

Using the erase() function with an Iterator

Another variant of the erase method allows removing an element pointed to by an iterator. This is particularly useful when you have already located the element using an iterator, for example, through a search operation.

Let’s see the complete example,

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

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

    // Look for element with key 'Where'
    auto it = wordFrequency.find("Where");

    // Check if iterator is valid
    if (it != wordFrequency.end())
    {
        // Removes the element pointed to by the iterator
        wordFrequency.erase(it); 
    }

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

    return 0;
}

Output:

Key: That :: Value: 19
Key: Why :: Value: 21

In this code, wordFrequency.find(“Where”) returns an iterator it pointing to the element with the key “Where”. If the iterator is not at the end of the map (i.e., the element is found), wordFrequency.erase(it) removes the element pointed to by it.

Using the erase() function with a Range of Iterators

The erase() function can also remove a range of elements from an unordered_map by accepting two iterators that specify the beginning and end of the range to be removed.

Let’s see the complete example,

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

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


    // Removes elements from the 
    // start iterator to the end iterator (exclusive)
    wordFrequency.erase(
                    wordFrequency.begin(),
                    wordFrequency.end()); 

    std::cout<< "Number of elements in Unordered_Map: " 
             << wordFrequency.size()
             << std::endl;

    return 0;
}

Output:

Number of elements in Unordered_Map: 0

In this case, wordFrequency.erase(wordFrequency.begin(), wordFrequency.end()) removes all elements from the map. The method takes two arguments: the starting iterator (wordFrequency.begin()) and the ending iterator (wordFrequency.end()). All elements in the range [first, last) are removed. Note that the ending iterator is exclusive, meaning the element pointed to by the ending iterator is not removed. However, since wordFrequency.end() points past the last element, all elements in the map are effectively removed.

Using the clear() function

This method removes all elements from the unordered_map, leaving it with a size of 0.

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

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


    // Removes all elements from unordered_map
    wordFrequency.clear();

    std::cout<< "Number of elements in Unordered_Map: " 
             << wordFrequency.size()
             << std::endl;

    return 0;
}

Output:

Number of elements in Unordered_Map: 0

Summary

We learned about different ways to remove elements from 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.