当通知的迭代器参数初始化为空列表的开头时,list :: insert行为是什么? [英] What is the list::insert behavior when the informed iterator argument is initialized to the begining of an empty list?

查看:30
本文介绍了当通知的迭代器参数初始化为空列表的开头时,list :: insert行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个C ++空列表:

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 << ' ';
}

获得的结果是: 10 20 30 .

但是,假设 insert 函数在迭代器指向的元素之前之前插入了元素,所以获得的结果应该是: 30 20 10 .

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.

为什么会这样?

推荐答案

如果列表为空,则 begin()迭代器与 end()迭代器进行比较.用 end()迭代器调用 insert()会将值插入列表的末尾.insert() 不会使任何迭代器失效,因此每次调用 时,您的 it 变量仍然持有 end() 迭代器insert().

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().

如果希望您的值与调用 insert()的顺序相反,请使用 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);

实时演示

这篇关于当通知的迭代器参数初始化为空列表的开头时,list :: insert行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆