Блог пользователя luka25

Автор luka25, история, 10 лет назад, По-английски

I just tried to delete some members from set while iterating with this code:

while(*it<=b){ if(*it!=x){m[*it]=x;s.erase(it);} else it++; }

I found out the right one was this, but can't figure out why

while(*it<=b){ if(*it!=x){m[*it]=x;s.erase(it++);} else it++; }

could anybody explain why it++ instead of it please?

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
10 лет назад, скрыть # |
← Rev. 4  
Проголосовать: нравится +4 Проголосовать: не нравится

Because if you look into set documentation erase method you'll find the following:

Iterators, pointers and references referring to elements removed by the function are invalidated. All other iterators, pointers and references keep their validity.

so s.erase(it) invalides it.

s.erase(it++) works, because it++ returns copy of iterator. For example,++it wouldn't work.