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 main(void)
{
std::vector<int> data;
int value = 0;
cout << "Enter a series of natural numbers (negative number to end):\n";
while(std::cin >> value, value >= 0)
data.push_back(value);
std::sort(data.begin(), data.end());
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";
return 0;
}
Enter a series of natural numbers (negative number to end):
15
17
19
21
-1
The two smallest numbers entered are 15 and 17.
15
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.
cout << "\nThe two smallest numbers entered are " << *iter << " and " << *(iter++) << ".\n\n";
^^^^^ (1) ^^^^^ (2)
The code under (2) writes to the variable iter (that's what post-increment does). the code under (1) reads from the same variable. This is, to put it simple, an error.
Seeing as you don't use the incremented iter again, perhaps you meant to write *(iter+1)?