Talles Brito
Talles Brito

Reputation: 33

What is the list::insert behavior when the informed iterator argument is initialized to the begining of an empty list?

Suppose you have a C++ empty list:

list<int> l;

and you insert three new elements from the beginning:

auto it = l.begin();
    l.insert(it,10);
    l.insert(it,20);
    l.insert(it,30);

when trying to print the list elements from the beginning to the end:

for(int i: l){
        cout << i << ' ';
}

the obtained result is: 10 20 30.

But it is supposed that insert function inserts elements before the element pointed by the iterator, so the obtained result should have been: 30 20 10.

Why does this happen?

Upvotes: 2

Views: 669

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596352

When the list is empty, the begin() iterator compares equal to the end() iterator. Calling insert() with the end() iterator inserts the value at the end of the list. insert() does not invalidate any iterators, so your it variable is still holding the end() iterator each time you are calling insert().

If you want your values to be in the reverse order that you call insert(), use the iterator that insert() returns to you, eg:

auto it = l.begin();
it = l.insert(it,10);
it = l.insert(it,20);
it = l.insert(it,30);

Live Demo

Upvotes: 3

Related Questions