C++ Hashmap Delete While Iterating
In C++, iterators can be used to traverse and delete elements in a hashmap. Here is a common approach:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> hashMap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}};
for(auto it = hashMap.begin(); it != hashMap.end();) {
if(it->first == 2) {
it = hashMap.erase(it);
} else {
++it;
}
}
for(auto& pair : hashMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
In the example above, we are using the iterator ‘it’ to traverse the hashmap and use the erase method to delete elements when a certain condition is met. It is important to note that after deleting an element, the iterator ‘it’ needs to be incremented to the next element to avoid skipping elements or causing undefined behavior during traversal.