C++ Remove an Entry Using Value from HashMap while Iterating over It

C++Server Side ProgrammingProgramming

Discuss how to remove an entry from HashMap using the value while iterating over it, for example

Input: HashMap: { 1: “ Mango ”,
2: “ Orange ”,
3: “ Banana ”,
4: “Apple ” }, value=”Banana”

Output: HashMap: { 1: “ Mango ”,
2: “ Orange ”,
4: “Apple ” }.

Explanation: The third key-value pair is removed using the value “banana”.

Input: HashMap: { 1: “Yellow”,
2: “White”,
3: “Green” }, value=”White”

Output: HashMap: { 1: “Yellow”,
3: “Green” }.

Approach to Find the Solution

In C++, We can remove the element using the .erase() function. From the erase() function, we can remove the element using the key name or using an iterator. In this tutorial, we will discuss removing elements using an iterator.

Here we will iterate through the hashmap and check whether every value is removed and remove the entry when the value is matched.

Example

C++ Code for the Above Approach

Remove Element while Iterating over HashMap

#include<iostream>
#include<map> // for map operations
using namespace std;
int main(){  
    // Creating HashMap.
    map< int, string > fruits;
    // Inserting key-value pair in Hashmap.
    fruits[1]="Mango";
    fruits[2]="Orange";
    fruits[3]="Banana";
    fruits[4]="Apple";
    string value = "Banana";
    // Creating iterator.
    map<int, string>::iterator it ;
    // Printing the initial Hashmap.
    cout<< "HashMap before Deletion:\n";
    for (it = fruits.begin(); it!=fruits.end(); ++it)
        cout << it->first << "->" << it->second << endl;
    for (it = fruits.begin(); it!=fruits.end(); ++it){
        string temp = it->second;
        // Checking iterator value with required value.
        if(temp.compare(value) == 0){
            // erasing Element.
            fruits.erase(it);

        }
    }
    // Printing Hashmap after deletion.
    cout<< "HashMap After Deletion:\n";
    for (it = fruits.begin(); it!=fruits.end(); ++it)
        cout << it->first << "->" << it->second << endl;
    return 0;
}

Output

HashMap before Deletion:
1->Mango
2->Orange
3->Banana
4->Apple

HashMap After Deletion:
1->Mango
2->Orange
4->Apple

Conclusion

In this tutorial, we discussed How to remove an entry from HashMap using value. We discussed the way to remove an entry by iterating over it. We also discussed the C++ program for this problem which we can do with programming languages like C, Java, Python, etc. We hope you find this tutorial helpful.

raja
Updated on 26-Nov-2021 06:10:13

Advertisements