Home >Backend Development >C++ >How Can I Safely Remove Elements from a C Map During Iteration?
Removing Elements from a Map During Iteration
In C , iterating over a standard library map while removing elements can be challenging, as using erase() invalidates iterators. However, there is a widely accepted idiom to address this issue:
for(auto it = m.begin(); it != m.cend() /* not hoisted */; /* no increment */) { if(must_delete) { auto next = it; it = m.erase(it); // or "it = m.erase(it)" since C++11 } else { ++it; } }
Here's how this idiom works:
Pre-C 11 Syntax:
Before C 11, erasing const iterators required a slightly different syntax:
for (std::map<K,V>::iterator it = m.begin(); it != m.end(); ) { /* ... */ }
Constness and Removal:
Erasing an element from a map does not violate the constness of the elements, similar to deleting a pointer-to-constant. Constness primarily constrains the ability to modify the value, not its lifetime.
The above is the detailed content of How Can I Safely Remove Elements from a C Map During Iteration?. For more information, please follow other related articles on the PHP Chinese website!