When iterating over an `std::unordered_map` in C++, you may encounter scenarios where you need to erase elements while still accessing the map. Directly modifying the container during iteration can lead to invalid iterators and undefined behavior. To handle this safely, you can make use of the iterator returned by the `erase` method of the unordered_map. This allows you to continue iterating through the remaining elements even after deleting some.
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map myMap = {
{1, "Apple"},
{2, "Banana"},
{3, "Cherry"},
{4, "Date"}
};
for (auto it = myMap.begin(); it != myMap.end(); ) {
if (it->second == "Banana") {
it = myMap.erase(it); // Erase and get next iterator
} else {
++it; // Just move to the next element
}
}
// Print remaining elements
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?