Dani Dani - 1 year ago 173
C++ Question

How to remove from a map while iterating it?

How do I remove from a map while iterating it? like:

std::map<K, V> map;
for(auto i : map)
// remove it from the map

If I use
it will invalidate the iterators

Answer Source

The standard associative-container erase idiom:

for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
  if (must_delete)

Note that we really want an ordinary for loop here, since we are modifying the container itself. The range-based loop should be strictly reserved for situations where we only care about the elements. The syntax for the RBFL makes this clear by not even exposing the container inside the loop body.

Edit. Pre-C++11, you could not erase const-iterators. There you would have to say:

for (std::map<K,V>::iterator it = m.begin(); it != m.end(); ) { /* ... */ }

Erasing an element from a container is not at odds with constness of the element. By analogy, it has always been perfectly legitimate to delete p where p is a pointer-to-constant. In other words yet, the destructor is always implicitly const.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download