While iterating through a set, or a map, you should not erase elements. When an element is erased, the iterator pointing to it becomes void, or not useable. If you want to do so, you have to do something like what you’ve done in the second code. Another way to do this is writing
it = m.erase(it) from C++11 (I think), the erase function returns a valid iterator pointing to the next element. You can also do
m.erase(it++). This erases
it, but as we do an increment, the value of
it changes before the element is erased and hence is now a valid iterator. Note the post increment operation which would pass the value of
erase() first, and then increment
Also format your code.