Home >Backend Development >C++ >What Happens When Erasing a Map Element During Iteration in C ?

What Happens When Erasing a Map Element During Iteration in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 15:24:11355browse

What Happens When Erasing a Map Element During Iteration in C  ?

What Happens When You Call erase() on a Map Element While Iterating from Begin to End?

In C 03, erasing an element in a map invalidates the iterator pointing to that element. However, in C 11 and later, the erase method returns the next iterator, allowing for safe iteration after element removal.

Solution for C 03

In C 03, to ensure safe iteration after removing elements from a map, update your code to use the iterator returned by map::erase() and perform post-increment on the iterator after calling erase().

map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();<br>while(pm_it != port_map.end())<br>{</p>
<pre class="brush:php;toolbar:false">if (pm_it->second == delete_this_id)
{
    port_map.erase(pm_it++);  // Use iterator.
                              // Note the post increment.
                              // Increments the iterator but returns the
                              // original value for use by erase 
}
else
{
    ++pm_it;           // Can use pre-increment in this case
                       // To make sure you have the efficient version
}

}

Solution for C 11 and Later

In C 11 and later, erase() returns the next iterator, making it safe to iterate and remove elements simultaneously using the following syntax:

<br>auto pm_it = port_map.begin();<br>while(pm_it != port_map.end())<br>{</p>
<pre class="brush:php;toolbar:false">if (pm_it->second == delete_this_id)
{
    pm_it = port_map.erase(pm_it);
}
else
{
    ++pm_it;
}

}

The above is the detailed content of What Happens When Erasing a Map Element During Iteration 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