<p>In the following code I loop through a map and test if an element needs to be erased.  Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?</p>

<pre><code>map&lt;string, SerialdMsg::SerialFunction_t&gt;::iterator pm_it;
for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++)
{
    if (pm_it-&gt;second == delete_this_id) {
        port_map.erase(pm_it-&gt;first);
    }
}
</code></pre>

<p>UPDATE: Of course, I then <a href="https://stackoverflow.com/questions/52714/stl-vector-vs-map-erase">read this question</a> which I didn't think would be related but answers my question.</p>

C++11
This has been fixed in C++11 (or erase has been improved/made consistent across all container types).
The erase method now returns the next iterator.
```
```
auto pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        pm_it = port_map.erase(pm_it);
    }
    else
    {
        ++pm_it;
    }
}
```
```
C++03
Erasing elements in a map does not invalidate any iterators.
(apart from iterators on the element that was deleted)
Actually inserting or deleting does not invalidate any of the iterators:
Also see this answer:
Mark Ransom Technique
But you do need to update your code:
In your code you increment pm_it after calling erase. At this point it is too late and is already invalidated.
```
```
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    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
    }
}
```
```