小编ate*_*rva的帖子

迭代器begin()应该包含3,输出说2?

为什么指向列表开头的迭代器输出第二个值?为什么a.begin()++会提前begin()并且有更好的实现?

#include <iostream>
#include <list>
using namespace std;
//3,2,1
int main() {
    list<int> a;
    a.insert(a.begin(),1);              
    cout << *(a.begin()) << endl;
    a.insert(a.begin(),3);
    cout << *a.begin()<< endl;
    a.insert(a.begin()++,2);
    list<int>::iterator iterator = a.begin();
    iterator++;
    cout << *iterator << endl;
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的输出:

1
3
3
Run Code Online (Sandbox Code Playgroud)

预期产量:

1
3
2
Run Code Online (Sandbox Code Playgroud)

编辑:"因为你把2放在列表的开头.请记住a.begin()++正在进行后递增,即在所有其他操作之后递增.使用++ a.begin()尝试你的代码并查看如果它符合你的期望" - @Ben

排版错误,谢谢Ben.

c++ stl std

-1
推荐指数
1
解决办法
82
查看次数

标签 统计

c++ ×1

std ×1

stl ×1