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
Release: 2024-12-16 15:24:11
Original
293 people have browsed it

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><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
}
Copy after login

}

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">if (pm_it->second == delete_this_id)
{
    pm_it = port_map.erase(pm_it);
}
else
{
    ++pm_it;
}
Copy after login

}

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!

source:php.cn
Previous article:How Can We Implement an ABA Counter in C 11 Using Only CAS? Next article:When Should You Use the `friend` Keyword in C for Encapsulation?
Statement of this Website
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
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template