Search code examples
c++iteratorinput-iterator

traversing a container a second time with an input iterator


there is no guarantee that traversing a container a second time with an input iterator will move through the values in the same order.Also after an input iterator has been incremented, there is no guarantee that its prior value can still be dereferenced.

or

An InputIterator is an Iterator that can read from the pointed-to element. InputIterators only guarantee validity for single pass algorithms: once an InputIterator i has been incremented, all copies of its previous value may be invalidated.

why all copies of its previous value may be invalidated ? what is the conceptual of these statement ?


Solution

  • What that is saying is that your iterator can only read the element that it is currently pointing to, it has no knowledge of previous or next elements.

    Think of having two iterators pointing to a std::list<T>

              Item1 ---> Item2 ---> Item3 ---> Item4
    Iter0 ----↑          ↑
    Iter1----------------ˈ
    

    Imagine incrementing these as follows:

    Iter0 = Iter1;
    Iter1++;
    

    After an increment, your set of iterators would look like this:

                 Item1 ---> Item2 ---> Item3 ---> Item4
    Iter0 ------------------↑          ↑
    Iter1------------------------------ˈ
    

    The previous value of Iter1 is stored into Iter0 so it always points to the element previous to Iter1.

    Now imagine that I perform a deletion of Item2.

                 Item1 ---> Item3 ---> Item4
    Iter0 -???              ↑
    Iter1-------------------ˈ
    

    Iter1 is still valid and points to Item3.

    Iter0 which was the previous value of Iter1 is no longer valid and points to "nothing" (meaning dereferencing this iterator would now be considered undefined behavior).