RED_in_Three_Months's blog

By RED_in_Three_Months, history, 5 years ago, In English

Why for(auto x:st)st.erase(st.find(x)); and for( it=st.begin();it!=st.end();it++)st.erase(it); causes runtime error??

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by RED_in_Three_Months (previous revision, new revision, compare).

»
5 years ago, # |
  Vote: I like it +20 Vote: I do not like it

Don't know about the first example. But for the second one, once you delete using the iterator it, the element gets deleted as well as all iterators pointing to that element. Thus it gets invalidated.

There's an easy workaround. set.erase(it) returns an iterator pointing to the element next to *it. So, you could just do it = set.erase(it).

This issue has been nicely discussed here: https://codeforces.net/blog/entry/55393