Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 551
qwlice Avatar asked Sep 08 '11 14:09

qwlice


People also ask

Is iterator valid after erase?

Every iterator and reference after the point of erasing is invalidated.

Why are iterators invalidated?

All iterators and the references are invalidated if the inserted item is not inserted at the end of the deque. If the items are deleted from any of the position except the end position, then all iterators will be invalidated. Same as like insert or erase.

Does map insert invalidate iterator?

Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased.

Does std :: move invalidate iterators?

No, they should not get invalidated after a move operation.


1 Answers

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

See Iterator invalidation rules

like image 115
Mark Ransom Avatar answered Sep 23 '22 00:09

Mark Ransom