When iterating through a `std::unordered_map` in C++, you may need to erase elements based on certain conditions. However, erasing elements while iterating can invalidate the iterator, leading to undefined behavior. To safely erase elements during iteration in a performance-sensitive context, you should use the `erase` function with the iterator returned by the `find` method or by using a temporary iterator. Here's how you can do it:
#include
#include
int main() {
std::unordered_map myMap = {
{1, "one"},
{2, "two"},
{3, "three"},
{4, "four"}
};
for (auto it = myMap.begin(); it != myMap.end(); ) {
if (it->first % 2 == 0) { // Erase even keys
it = myMap.erase(it); // erase returns the next iterator
} else {
++it; // Increment iterator
}
}
// Output 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?