-1

I have a map with following key value pairs. {(a,P),(b,Q),(c,R),(d,S),...(g,Z)}

I'm iterating this map and at each element I take a branch which access this same map and erase an element of the map if a condition is met. Simply put, it is possible that while the main iterator is at (b.Q) , the branching function can erase (d,S).

Is this valid.? Or will this seg fault.?

Pasan W.
  • 674
  • 2
  • 10
  • 23

1 Answers1

5

You need to read the iterator invalidation rules:

std::map::erase

References and iterators to the erased elements are invalidated. Other references and iterators are not affected.

So as long as you don't use the iterator where you erased, you are good.

bolov
  • 72,283
  • 15
  • 145
  • 224
  • So what happens when the main function "reaches" (d,S) when it was already deleted ? – Pasan W. Dec 02 '15 at 17:19
  • 1
    After you erase an element (e.g. (d, S)) that element is not part of the container anymore. You will never reach it again by iterating through the container. CARE: if you have an iterator to (d, S) obtained before the erase, that iterator is invalidated, so you can't use it anymore. – bolov Dec 02 '15 at 17:21
  • But it says invalidation doesn't happen in C++ 03.. And I do get a seg fault with "Double Free or Corruption" – Pasan W. Dec 02 '15 at 17:29
  • 1
    @PasanW Ofc it happens. Read again. Quoting from the answer: «Erasing elements in a map does not invalidate any iterators. (**apart from iterators on the element that was deleted**)» – bolov Dec 02 '15 at 17:34
  • 1
    @PasanW If you get a runtime error then you either still use the iterator to the erased element, or you have another bug in your code. Post another question with a [MCVE] exhibiting the error. – bolov Dec 02 '15 at 17:35