Why does the iterator pointing to the beginning of a list output the second value? Why does a.begin()++ leave begin() ahead and is there a better implementation?
#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;
}
My output:
1
3
3
Expected output:
1
3
2
Edit: "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
Typographic error, thanks Ben.