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

Suppose we have a map like this,

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

Now we will see how to remove certain key-value pairs from this map by its key. There are different ways to do that, let’s discuss them one by one.

Using the erase() Function with a Key

The erase() function in C++’s map provides a way to remove elements based on their keys.

It accepts a key as an argument and erases all the elements located by the given key in the map. It returns the number of elements erased. As a map can have only unique keys, it will either return 0 if the given key does not exist in the map, or it will remove the key and return the value 1 if the key exists.

Let’s see an example,

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

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

Using the erase() Function with an Iterator

Another variant of the erase() method allows for the removal of an element pointed to by an iterator. It accepts an iterator as an argument and removes the key-value pair pointed to by that iterator.

In the below example, we will look for a key-value pair by its key using the find() function. It will return an iterator pointing to that key-value pair. If the returned iterator is valid, then we will pass it to the erase() function to remove that key-value pair from the map.

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

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

Using the erase() Function with a Range of Iterators

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

In the below example, we will create a map and initialize it with some default key-value pairs. Then we fetch two iterators pointing to the start and end of the map and pass them to the erase() function of the map. It will remove all elements from the map. Let’s see the complete example:

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

int main() 
{
    std::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 Map: " 
             << wordFrequency.size()
             << std::endl;

    return 0;
}

Output:

Number of elements in Map: 0

Using the clear() Function

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

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

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

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

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

    return 0;
}

Output:

Number of elements in Map: 0

Summary

We learned about different ways to remove elements from a map in C++. Unlike unordered_map, a map maintains a sorted order based on keys, which can affect the order of iteration, but the methods to remove elements are quite similar.

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.