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