开发者

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

开发者 https://www.devze.com 2023-04-03 08:23 出处:网络
This question already has answers here: Iterator invalidation rules for C++ containers (6 answers) Closed 4 years ago.
This question already has answers here: Iterator invalidation rules for C++ containers (6 answers) Closed 4 years ago.

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 ?


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消