Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End iterator invalidation rules

Tags:

c++

iterator

Regarding this question on iterator invalidation rules, it seems obvious that the spirit of the standard means, for example, that "an erase in the middle of the deque invalidates all the iterators and references to elements of the deque" also refers to the end iterator.

However, I can't find anywhere that the standard makes this explicit, and strictly speaking the end iterator is not an iterator to an element in the container.

Does the 2003 standard make this clear somewhere?

like image 708
Lightness Races in Orbit Avatar asked Jun 22 '11 13:06

Lightness Races in Orbit


People also ask

How can we avoid iterator invalidation?

To avoid invalidation of references to elements you can use a std::deque if you do not insert or erase in the middle. To avoid invalidation of iterators you can use a std::list.

Does iterator delete invalidate?

No; all of the iterators at or after the iterator(s) passed to erase are invalidated. However, erase returns a new iterator that points to the element immediately after the element(s) that were erased (or to the end if there is no such element). You can use this iterator to resume iteration.

Does map insert invalidate iterator?

Inserting into std::map does not invalidate existing iterators.


1 Answers

For example, 23.1/10:

no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ]

I do not know if we can be certain that iterator referring to an element has been used consistently in the Standard to exclude end iterators :/

As said in a comment, I suppose this is to allow end iterators pointing to sentinel values within the container.

For example, a typical doubly linked List implementation is to create a Node structure, and have one Node by value within the List to act as the end node.

like image 109
Matthieu M. Avatar answered Oct 13 '22 01:10

Matthieu M.