How do I erase elements while iterating with std::map in multithreaded code?

In C++, when iterating through a `std::map` in a multithreaded environment, erasing elements requires careful handling to avoid undefined behavior. You'll want to ensure that no iterators are invalidated and that thread safety is maintained. Below is an example demonstrating how to safely remove elements from a `std::map` while iterating through it in a multithreaded context.

#include #include #include #include std::map my_map; std::mutex mtx; void modify_map() { std::lock_guard<:mutex> lock(mtx); // Insert an element my_map[1] = 100; my_map[2] = 200; my_map[3] = 300; } void iterate_and_erase() { std::lock_guard<:mutex> lock(mtx); for(auto it = my_map.begin(); it != my_map.end(); ) { if(it->second < 200) { it = my_map.erase(it); // Erase returns the next iterator } else { ++it; // Only increment if not erasing } } } int main() { std::thread t1(modify_map); std::thread t2(iterate_and_erase); t1.join(); t2.join(); for(const auto& pair : my_map) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

C++ std::map multithreading erase elements thread safety