How do I erase elements while iterating with std::map for large datasets?

In C++, when working with large datasets using `std::map`, you might encounter situations where you need to erase elements while iterating through the map. Doing this safely is important to avoid invalidating iterators, which can lead to undefined behavior. Below is an example demonstrating how to properly erase elements from a `std::map` using iterators.

#include #include int main() { std::map myMap = { {1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"} }; // Iterate and erase elements for (auto it = myMap.begin(); it != myMap.end(); ) { if (it->first % 2 == 0) { // Example condition: remove even keys it = myMap.erase(it); // Erase and get the next valid iterator } else { ++it; // Increment only if not erasing } } // Output remaining elements for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

C++ std::map erase elements iterator large datasets remove elements C++ examples