In C , iterating through a map and erasing elements can raise concerns regarding iterator validity. The behavior varies based on the C version used.
In C 11, the erase() method has been enhanced to return the iterator to the subsequent element. This simplifies the process:
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 does not automatically invalidate iterators. However, the iterator pointing to the deleted element becomes invalid. To maintain iterator validity, the code must be updated:
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 } else { ++pm_it; } }
Here, the post-increment operator ( ) is used in the erase() call to ensure that the returned iterator points to the correct element.
The above is the detailed content of What are the Implications of Removing Map Elements While Iterating in C ?. For more information, please follow other related articles on the PHP Chinese website!