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

扶醉桌前 提交于 2019-12-06 01:11:26

问题


when and how are iterators invalidated in a map when using the erase method ?

for example :

std :: map < int , int > aMap ;

aMap [ 33 ] = 1 ;
aMap [ 42 ] = 10000 ;
aMap [ 69 ] = 100 ;
aMap [ 666 ] = -1 ;

std :: map < int , int > :: iterator itEnd = aMap.lower_bound ( 50 ) ;

for ( std :: map < int , int > :: iterator it = aMap.begin ( ) ;
      it != itEnd ;
      // no-op
    )
{
   aMap.erase ( it ++ ) ;
}

the erased iterator will surely become invalid (it's incremented while still valid) but what about the others?

if I'm not wrong the standard says that a map has to be a balanced binary tree or a structure with equivalent key-search complexity

in case the map is implemented with a tree, can I assume that not erased iterators remain valid ?

what about other possible ways to implement a map ?


回答1:


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

See Iterator invalidation rules




回答2:


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?



来源:https://stackoverflow.com/questions/7349899/how-are-map-iterators-invalidated-when-erasing-elements

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