How do I erase elements while iterating with std::map in performance-sensitive code?

When working with std::map in C++, it's crucial to manage performance effectively, especially when modifying the map while iterating over its elements. The std::map container provides a convenient way to store key-value pairs, but directly erasing elements during iteration can lead to issues such as invalidating iterators. To maintain performance and avoid potential pitfalls, we can use a safe iteration technique.

Keywords: C++, std::map, erase elements, iteration, performance, safe iteration
Description: This article discusses how to safely erase elements from a std::map while iterating, ensuring performance is maintained in critical code sections.

// Example of safely erasing elements from std::map while iterating
#include <iostream>
#include <map>

int main() {
    std::map myMap;
    // Populating the map
    for (int i = 0; i < 10; ++i) {
        myMap[i] = i * 10;
    }

    // Iterating and erasing elements
    for (auto it = myMap.begin(); it != myMap.end(); ) {
        if (it->second > 50) { // Example condition to erase elements
            it = myMap.erase(it); // Erase returns the next iterator
        } else {
            ++it; // Only increment if not erasing
        }
    }

    // Print remaining elements
    for (const auto& pair : myMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}
    

Keywords: C++ std::map erase elements iteration performance safe iteration