When iterating through a map in C , it's important to consider the behavior of erasing elements while iterating. This operation may lead to unexpected results if not handled correctly.
In C 11, the erase() method has been improved and is now consistent across all container types. When an element is erased, the erase() method returns the next iterator. This allows you to continue iterating the map without encountering any problems.
The following code demonstrates the correct way to erase elements from a map while iterating in C 11:
auto pm_it = port_map.begin(); while (pm_it != port_map.end()) { if (pm_it->second == delete_this_id) { pm_it = port_map.erase(pm_it); } else { ++pm_it; } }
In C 03, erasing elements from a map while iterating can lead to invalidated iterators. To avoid this issue, you should iterate through the map using a loop variable that is incremented outside of the erase() operation.
The following code demonstrates the correct way to erase elements from a map while iterating in C 03:
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin(); while (pm_it != port_map.end()) { if (pm_it->second == delete_this_id) { port_map.erase(pm_it++); // Use iterator. // Note the post increment. // Increments the iterator but returns the // original value for use by erase } else { ++pm_it; // Can use pre-increment in this case // To make sure you have the efficient version } }
The above is the detailed content of What Happens When You Erase a Map Element During Iteration in C ?. For more information, please follow other related articles on the PHP Chinese website!