C++

C++ Std::Map::Erase Examples

Among the many operations available for “std::map”, the “erase” function stands out as a crucial tool for removing the elements based on their keys. An “std::map” is an organized associative container that comprises of key-value pairs. The arrangement of elements within an “std::map” is consistently sorted according to their keys, facilitating the effective operations such as search, insertion, and deletion based on key values.

Within the realm of C++, the “std::map::erase” function serves as a member function of the “std::map” class, enabling the elimination of specific elements from the map. It comes in various forms, providing flexibility in specifying which elements to erase. In this article, we will delve into the details of “std::map::erase”, providing multiple examples to illustrate its versatility.

Example 1: Erasing by Key

The ability to erase the elements by key in the “std::map” is a fundamental feature provided by the C++ Standard Template Library. This operation is commonly used when you need to manage and manipulate the key-value pairs in a program, and it provides a convenient way to remove the specific elements based on their keys. We will create an example to demonstrate how to use the “std::map” to create a map, erase an element by key, and then display the modified map.

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;
    myMap[1] = "Red";
    myMap[2] = "Blue";
    myMap[3] = "Green";

    myMap.erase(2);

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

    return 0;
}

 
In this example, we begin by including the necessary C++ standard libraries such as <iostream> and <map> to enable the use of input/output operations and the “std::map” container, respectively.  Within the “main” function, we initialize the “std::map” named “myMap” where the integer keys are associated with corresponding string values. Three key-value pairs are added to the map that represent the colors: “Red” for key 1, “Blue” for key 2, and “Green” for key 3. Then, we use the “erase” member function of the “std::map” class to remove the element associated with the key 2 from our map. Consequently, the “Blue” color is no longer part of the map after this operation.

To showcase the resulting state of the map, we employ a “for” loop that iterates through each key-value pair within “myMap”. We utilize the “std::cout” object inside the loop to print each key-value pair to the console. Finally, the “return 0” statement concludes the “main” function which signals the successful execution of our program.

The output displays the remaining key-value pairs in the “std::map” after the element with key 2 (“Blue”) is erased which results in the “1: Red” and “3: Green” output.

Example 2: Erasing by Iterator

In C++, iterators are objects that facilitate the navigation of elements within a container, offering a means to access, modify, or remove the elements.  The “std::map::erase” function can also be used with iterators to remove the elements.

Here’s an example:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> fruitMap;
    fruitMap[1] = "Mango";
    fruitMap[2] = "Orange";
    fruitMap[3] = "PineApple";
    fruitMap[4] = "Grapes";
   
    auto it = fruitMap.find(2);

    if (it != fruitMap.end()) {
        fruitMap.erase(it);
    }

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

    return 0;
}

 
The provided C++ code begins by declaring an “std::map” named “fruitMap” to store the key-value pairs, associating the integers with corresponding fruit names. We populate the map with entries for four different fruits: “Mango”, “Orange”, “PineApple”, and “Grapes”. After that, we utilize the “find” function to obtain an iterator (it) that points to the element with the key value of 2 within the “fruitMap”. Then, we check if the iterator is not equal to “end()” to ensure that the element with the specified key exists in the map.

In the conditional block, we erase the element that is pointed to by the “it” iterator using the “erase” function. Finally, we iterate through the remaining elements in the modified “fruitMap” using a “for” loop.

The final output displays the modified “fruitMap” contents after the erasure.

Example 3: Erasing a Range

The “std::map” container in C++ provides a convenient method to erase the elements within a specified range. The “erase” function allows you to remove the elements from the map based on iterators that represent the beginning and end of the range to be deleted.

Now, let’s explore the concept of erasing a range using “std::map” with an example:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> newMap;
    newMap[1] = "Horse";
    newMap[2] = "Lion";
    newMap[3] = "Tiger";
    newMap[4] = "Cat";
   
    newMap.erase(newMap.lower_bound(2), newMap.upper_bound(3));

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

    return 0;
}

 
The program begins by declaring an “std::map” named “newMap” which associates the integer keys with corresponding string values. After that, we populate the map with key-value pairs using the square bracket operator. For instance, we assign the key-value pairs of (1, “Horse”), (2, “Lion”), (3, “Tiger”), and (4, “Cat”) to “newMap”.

The next significant operation involves using the iterators to erase the elements from the map. The erase function is employed with the “newMap.lower_bound(2)” and “newMap.upper_bound(3)” arguments. This erases the elements with keys that fall in the range (2, 3). In other words, it removes the “Lion” and “Tiger” entries from the map. After this operation, the map contains only the elements with keys 1 and 4, corresponding to “Horse” and “Cat”.

Finally, we use a range-based “for” loop to iterate through the remaining elements in the map and print their key-value pairs to the console.

As a result, the output displays the following:

Example 4: Erasing Based on a Predicate

Erasing based on a predicate refers to removing the elements from a data structure, such as a container, based on a specified condition or criteria. The “std::map::erase” can also be used with a predicate function to remove the elements conditionally. Let’s consider the following example:

#include <iostream>
#include <map>
#include <algorithm>

int main() {

    std::map<int, std::string> myMap = {
        {1, "January"},
        {2, "February"},
        {3, "March"},
        {4, "April"},
        {5, "May"}
    };

    auto predicate = [](const std::pair<int, std::string>& element) {
        return element.second.length() < 5;
    };

    myMap.erase(std::remove_if(myMap.begin(), myMap.end(), predicate), myMap.end());

    std::cout << "\nMap after erasing elements based on the predicate:" << std::endl;
    for (const auto& pair : myMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}

 
The program begins by including the necessary header files. An “std::map” called “myMap” is declared and initialized in the “main” function. It contains the key-value pairs that represent the months’ names and their respective numerical values. Subsequently, a “lambda” function (predicate) is defined. This “lambda” function serves as a predicate for the “std::remove_if” algorithm. It verifies if the length of the string value that is associated with a map element is less than five characters.

The “std::remove_if’ algorithm is then used in conjunction with the “erase” function of the “std::map”. This combination removes the elements from the map based on the validity of the predicate.

After running the program, the elements with keys less than five are removed from the original map, demonstrating the erasing based on a predicate using “std::map”.

Conclusion

In conclusion, the “std::map::erase” function is a versatile tool in C++ to remove the elements from “std::map”. Whether erasing by key, iterator, range, or based on a predicate, the “std::map::erase” function provides flexibility and ease of use. By mastering this function, the C++ developers can efficiently manage and manipulate the data within “std::map”containers, making their code stronger and easier to maintain.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content