Alexander Torstling
Alexander Torstling

Reputation: 18898

Validity of list begin iterator after insertion

Consider the following program:

#include <list>
#include <cstdio>

int main() {
    std::list<int> l;
    std::list<int>::iterator it = l.begin();
    l.push_back(0);
    l.insert(it, 1);
    for(const int &i: l) {
        printf("%d", i);
    }
}

(http://cpp.sh/66giy)

This prints 01. Very surprising. If I change the list to a deque, it prints the expected 10.

Is this a bug?

EDIT: The deque behavior is irrelevant, iterators to deques are invalidated by push_back.

Upvotes: 5

Views: 870

Answers (1)

Klaus
Klaus

Reputation: 25613

I can't catch your problem... ok, lets try to reproduce:

std::list<int> l;
std::list<int>::iterator it = l.begin();

What is your iterator pointing to? To the end of the list as the list is empty!

§23.2.1 [container.requirements.general] p6

begin() returns an iterator referring to the first element in the container. end() returns an iterator which is the past-the-end value for the container. If the container is empty, then begin() == end();

l.push_back(0);

Now the list contains a single element. Your iterator is valid as a list did not invalidate the iterator and points still to the end of the list.

l.insert(it, 1);

Now you insert 1 before the iterator which points still to the end. So your first element is a 0 and the last one is a 1.

So your output is 01 as expected.

Maybe your expectation that the begin() delivers a fixed virtual start of container iterator is simply wrong?

Upvotes: 3

Related Questions