how are map iterators invalidated when erasing elements? [duplicate]

笑着哭i 提交于 2019-12-04 06:40:36
Mark Ransom

Only the erased iterator is invalid, the rest are guaranteed by the standard to remain valid.

See Iterator invalidation rules

If the map were to be implemented as a balanced tree, after doing erase, the tree might need to be rebalanced, that means that the positions an iterator was pointing to, could now have something else or nothing there, depending on the rebalancing of the tree, so that's why that iterator is invalidated when you remove an element from the map, having erased the element, the iterator now ends up pointing at some memory that is no longer valid, which is Undefined Behaviour.

What if you decide to remove all elements from the map, inside your loop, what are the iterators gonna end pointing at?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!