You are using a version without Ads of this website. Please, consider donating:

### Trouble with *(iterator++)

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?

 ``123456789101112131415161718192021222324252627`` ``````int main(void) { std::vector 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 ```

`... << *iter << " and " << *(iter++) `

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.

See http://en.cppreference.com/w/cpp/language/eval_order for some details
Last edited on
I am sorry, but I still do not fully understand the problem. Could you elaborate on this issue a bit more?
on line 19, you have:
 ``12`` ``````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)`?
Yes, I indeed meant to write the latter. I now understand the problem. Thank you, Ill mark the topic as solved.
Topic archived. No new replies allowed.