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

Автор taap_cader, история, 3 года назад, По-английски

iterator to any element in set belongs to address or value in c++? For example, my set is {1,2,3,4,5} and *it =3; So, here it is pointing to 3 or address where three is stored? I have tried it in my compiler, even after deleting 3 from set *it is still showing 3. How is this possible? And when I did it-- *it shows 2. And after it++, it directly jumps to 4. I have searched over internet but didn't find anything satisfying.

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

»
3 года назад, # |
  Проголосовать: нравится +31 Проголосовать: не нравится

std::set is red-black tree (not guaranteed but I don't know any other implementation). So iterator in set belongs to node in tree. Node contains item.

When you do smth like s.erase(it) node in tree is delete. it is invalid iterator. So any operation with it is meaningless and UB. But one can guess that node deleting is just mark that memory used by node is free and rebalance tree. So if memory under it not changed then it undestandable that *it returned 3. And there can be that --it returned 2 (node must contain ptr to parent node).

But again — don't do UB and don't guess why UB code do something.