Loop through unordered_map – CPP Unordered_Map: Erase Elements While Iterating in a Loop | Remove Entries from an Unordered Map While Iterating it in C++

Loop through unordered_map: In the previous article, we have discussed CPP11 / CPP14 : ‘delete’ keyword and deleted functions with Use Case. Let us learn What exactly is Unordered_Map in C++, How to Erase Elements while Iterating in a Loop. We have followed a step-by-step approach to help you understand the CPP Program for Unordered Map Erasing Elements while Iterating in a Loop. Try to apply the related knowledge when you encounter any such CPP Programs in your learning process.

Unordered_Map

Iterate through unordered_map c++: An associative container containing key-value pairs with unique keys is known as an unordered map. The average constant-time complexity of element search, insertion, and removal is high.

Internally, the elements are organized into buckets rather than being sorted in any particular order. The hash of an element’s key determines which bucket it is placed in. Because the hash refers to the exact bucket the element is placed into after it is computed, this allows for quick access to individual elements.

Given a unordered_map, the task is to erase elements from it while iterating through it.

Examples:

Input:

 { "Hello", 50 }, { "This", 100 }, { "is", 150 }, { "BTech", 220 }, { "Geeks", 250 }

Output:

Unordered map before modifying elements:
Geeks = 250
BTech = 220
is = 150
This = 100
Hello = 50
Unordered map after removing values which are greater than 200 :
is = 150
This = 100
Hello = 50

How to Remove Elements from unordered_map while Iterating through it in C++?

C++ unordered_map erase: Assume we have an unordered map with key-value pairs of string and integers.

We now want to remove all elements with values greater than 200. So, in order to delete all of those elements, we must iterate over the map to find them. As a result, we want to remove all of those elements in a single iteration.

To delete an element with an iterator, we will use the unordered map erase() function, which accepts an iterator and deletes that element, i.e.

iterator erase ( const_iterator position );

However, if the element is deleted, the iterator’s “position” becomes invalid. So, how do we get to the next element in the loop?

To get around this issue, The erase() function returns an iterator to the last deleted element’s next element. We’ll make use of it.

itr = stringmap.erase(itr);

Below is the implementation:

C++ Program to Remove element from unordered_map while iterating through it

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // create and intialize unordered_map with strings as
    // keys and integer as values
    unordered_map<std::string, int> stringmap(
        { { "Hello", 50 },
          { "This", 100 },
          { "is", 150 },
          { "BTech", 220 },
          { "Geeks", 250 } });
    cout << "Unordered map before modifying elements:"
         << endl;
    for (auto element : stringmap)
        cout << element.first << " = " << element.second
             << endl;
    // Taking a iterator which points to first key of the
    // unordered map
    unordered_map<std::string, int>::iterator itr
        = stringmap.begin();
    // erasing all elements whose value is greater than 200
    while (itr != stringmap.end()) {
        // checking if the value is greater than 200
        if (itr->second >= 200) {
            // erasing the element using erase() function
            itr = stringmap.erase(itr);
        }
        else
            itr++;
    }
    // printing the unordered_map
    cout << "Unordered map after removing values which are "
            "greater than 200 :"
         << endl;
    for (auto element : stringmap)
        cout << element.first << " = " << element.second
             << endl;
    return 0;
}

Output:

Unordered map before modifying elements:
Geeks = 250
BTech = 220
is = 150
This = 100
Hello = 50
Unordered map after removing values which are greater than 200 :
is = 150
This = 100
Hello = 50

Related Programs: