taap_cader's blog

By taap_cader, history, 4 months ago, In English

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.

 
 
 
 
  • Vote: I like it
  • +2
  • Vote: I do not like it

»
4 months ago, # |
  Vote: I like it +31 Vote: I do not like it

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.