问题
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