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

ぃ、小莉子 提交于 2021-01-28 13:46:35

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/61925270/what-is-the-listinsert-behavior-when-the-informed-iterator-argument-is-initial

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!