I am trying to get a handle on iterators and vectors so I wrote a small program utilizing a vector to return the lowest two values in a sequence of natural numbers. As far as I understand iterators, they are similar to pointers so that *iterator would point to the first element of the vector (so the lowest value in my program). To my surprise, this no longer holds when I implement the postfix increment operator *(iterator++). For some reason the lowest values are now displayed in reversed order. Could someone please explain this strange behavior to me?
int value = 0;
cout << "Enter a series of natural numbers (negative number to end):\n";
while(std::cin >> value, value >= 0)
cout << "The two smallest numbers entered are " << data.at(0) << " and " << data.at(1) << ".\n";
auto iter = data.begin();
cout << "\n" << *iter << "\n"; // Here *iter == lowest value, so far so good
cout << "\nThe two smallest numbers entered are " << *iter << " and " << *(iter++) << ".\n\n"; // Here *iter != lowest value but *(iter++) does
for(auto iterator = data.begin(); iterator != data.end(); iterator++)
cout << " " << *iterator << " ";
cout << "\n\n";
Enter a series of natural numbers (negative number to end):
The two smallest numbers entered are 15 and 17.
The two smallest numbers entered are 17 and 15.
15 17 19 21
this increments and reads iter in the same expression, without synchronization. You cannot predict which happens first, and if your vector iterators are typedefs for raw pointers (as they are in some implementations' release builds), this is completely undefined.