0

Deleting elements while iterating over them from an unordered_set gives unexpected results in C++.

unordered_set<int> s({1,2,3});
for(int curr : s) {
   s.erase(curr);
}

This gave an error in leetcode - "AddressSanitzer: heap-use-after-free...". And on onlinegdb, it gave unexpected results - some elements (last inserted element) were deleted, some were still in the set.

Why is this happening?

Parth Kapadia
  • 507
  • 6
  • 18
  • 2
    You're deleting element while iterating it. [Deleting elements from std::set while iterating](https://stackoverflow.com/questions/2874441/deleting-elements-from-stdset-while-iterating) – Jason Sep 15 '22 at 07:08
  • 2
    You can't do anything that invalidates the range in a range based loop. – Hackjaku Sep 15 '22 at 07:13
  • I understand why deleting an iterator can cause a problem as we are incrementing (it++) when we deleted `it` in the last step. But this happens in the foreach loop too, so does that work in a similar way? I thought curr is a separate integer independent of the set and hence deleting `s.erase(curr)` won't cause issues. Also, why does deleting an iterator while looping works for vector but not for set? – Parth Kapadia Sep 15 '22 at 07:26
  • 1
    @ParthKapadia Note that if the program has undefined behavior it means *"anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash"*. – Jason Sep 15 '22 at 07:33
  • 1
    @ParthKapadia It doesn't work for vector either, you just might get lucky. Yes, `curr` is independent but how do you get the next one? Through a hidden iterator which gets invalidated. – Quimby Sep 15 '22 at 07:33

0 Answers0