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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-12 15:20:11644browse

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

Removing Elements from a Map During Iteration

When iterating through a map, the common approach is to use a range-based for loop. However, modifying the map while iterating can lead to unexpected behavior, as the iterators will become invalid.

The recommended technique to remove elements from a map while iterating is known as the "associative-container erase 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 ensures that the iterator remains valid after the element is removed by using the prefix increment operator.

Note that it is important to use a traditional for loop instead of a range-based for loop in this case, as modifying the container will invalidate the iterators of the range-based loop.

Prior to C 11, it was necessary to use a separate iterator type when iterating through a map to remove elements:

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

In both cases, erasing an element does not violate the constness of the element, as constness in C does not affect the lifetime of an object.

The above is the detailed content of How to Safely Remove Elements 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