Home >Backend Development >C++ >How Can I Safely Remove Elements from a Map While Iterating in C ?

How Can I Safely Remove Elements from a Map While Iterating in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 17:00:12634browse

How Can I Safely Remove Elements from a Map While Iterating in C  ?

Safe Map Iteration with Element Removal

When working with maps, you may encounter the need to remove elements while iterating over them. However, using the map's erase() method directly within a loop can invalidate iterators. To avoid this issue, employ the following idiom:

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;
  }
}

This idiom uses a non-range-based for loop to modify the container directly. By incrementing the iterator inside the loop only when the element should not be removed, we maintain the integrity of the iteration.

Note that prior to C 11, erasing const iterators required a slightly different syntax:

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

Remember that removing elements does not violate constness, as const elements can still stop existing.

The above is the detailed content of How Can I Safely Remove Elements from a Map While Iterating in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn