Removing Items from a Map During Iteration in C
When iterating through a map and attempting to remove items based on specific conditions, it is important to consider the impact of erasing elements on the iterator. Erasing an element while iterating over the map will invalidate the iterator, making it difficult to continue the iteration process.
Standard Erasing Idiom for Associative Containers
The standard idiom for erasing from an associative container (such as a map) while iterating is as follows:
for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */) { if (must_delete) { m.erase(it++); // or "it = m.erase(it)" since C++11 } else { ++it; } }
Explanation
By following this idiom, you can safely remove items from the map while iterating without invalidating the iterators.
The above is the detailed content of How to Safely Remove Items from a C Map During Iteration?. For more information, please follow other related articles on the PHP Chinese website!