2

In c++ , what happens to the iterators when an element is added or deleted.

For example, vector is :{1,2,3,4,5,6} and suppose two iterators a and b point to element '2', and '5'. If I delete 3rd item i.e. delete '3', what will the iterators be pointing to ?

And if the iterator points to the last element, and that element gets deleted, will it cause error? I need to implement this code, where the elements are randomly deleted, i wanted to know the best /suitable data structure in which references doesn't change after the insertion ordeletion.

1 Answers1

-1

i guess what you are looking for is iterator invalidation: https://www.geeksforgeeks.org/iterator-invalidation-cpp/#:~:text=Resizing-,a.,it%20is%20supposed%20to%20point. check this link.

The summary is: if you delete element in vector, all the iterators pointing to the elements after deleted element gets changed. The iterator to the deleted element gets invalidated. Sometimes the program crashes and sometimes it just shows unpredictable answer.

the rules are different for other containers/sequence.

Suniti Jain
  • 382
  • 2
  • 10