Home >Backend Development >C++ >How to Safely Remove Items from a C Map During Iteration?

How to Safely Remove Items from a C Map During Iteration?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 00:38:09466browse

How to Safely Remove Items from a C   Map During Iteration?

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

  • Unhoisting the loop condition: This ensures that the loop checks for the end of the map each time through.
  • Not incrementing the iterator in the removal case: When an element is removed, the iterator points to the next element in the map. This means that the loop should not increment the iterator after erasing.
  • Const iterators: In pre-C 11, const iterators could not be erased. In this case, a traditional iterator (e.g., std::map::iterator) should be used.

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!

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