C++ Remove Elements From an Unordered Map

h‮//:sptt‬www.theitroad.com

To remove an element from an unordered map in C++, you can use the erase() function, which takes an iterator to the element to be removed.

Here's an example:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};

    // Print the original map
    for (const auto& element : myMap) {
        std::cout << element.first << ": " << element.second << std::endl;
    }

    // Remove the element with key "banana"
    myMap.erase("banana");

    // Print the updated map
    for (const auto& element : myMap) {
        std::cout << element.first << ": " << element.second << std::endl;
    }

    return 0;
}

Output:

apple: 1
banana: 2
orange: 3
apple: 1
orange: 3

In this example, we create an unordered map called myMap with three key-value pairs. We use a range-based for loop to print the original map. Then, we remove the element with key "banana" using the erase() function. Finally, we print the updated map using another range-based for loop. Note that the element with key "banana" is no longer present in the map.