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

Iterator begin() should contain 3, output says 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;
}

我的输出:

1
3
3

预期输出:

1
3
2

编辑: "Because you put 2 at the start of the list. Remember that a.begin()++ is doing post-incrementing ie, it increments after all other operations. Try your code with ++a.begin() and see if it does what you expect"- @Ben

排版错误,谢谢 Ben。

代码没问题:

#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();
    cout << *iterator << endl;
    return 0;
}

输出:

1
3
2

也在 Ideone 检查。

看起来这只是忘记了 a.insert(a.begin()++,2); 在这种情况下等同于 a.insert(a.begin(), 2)。这是因为 post-increment 会将 2 添加到列表的开头,然后递增迭代器。如果您想要预期的输出,那么您将需要使用预递增运算符。即:

a.insert(++a.begin(), 2)