2

just wondering if I have a map declared like this,

map<int, int> my_map;

and assign end() iterator to a variable, and never change,

auto end_it = my_map.end()

Then later I will change my_map by having many erase and insert of my_map, will the below always stays true during the life time of my_map?

end_it == my_map.end()
tesla1060
  • 2,621
  • 6
  • 31
  • 43

2 Answers2

5

std::map::insert guarantees:

No iterators or references are invalidated.

std::map::erase guarantees:

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

Therefore the end iterator should stay valid. If you use any other operation, you should check whether it might invalidate the iterators.

VLL
  • 9,634
  • 1
  • 29
  • 54
1

std::map::swap does invalidate the end() iterator:

All iterators and references remain valid. The end() iterator is invalidated.

phinz
  • 1,225
  • 10
  • 21