If you want to save memory, don't use std::map
, nor std::list
- use std::vector
; or better yet - don't use separate strings, apply de-duplication etc.
Having said that, and to answer your question: Deleting an element from a map invalidates iterators into the map - and the ranged-for loop is actually based on iterators. So - you can't delete during your loop. Use differences_map.clear()
after the loop. You should also note that individual element deletions are much more expensive time-wise than clearing the entire map.
If your memory is so constrained that you can't take having both the full map and the full list at the same time, then you are simply using the wrong data structures - since, like I said, both of these are quite wasteful. Still, if you insist, you could repeatedly insert *differences_map.begin()
into the list, then delete it from the map (and every time obtain .begin()
again, after iterator invalidation).