Supposedly:
for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
{}
I do understand the difference when it comes to pre/post increment for built-in types like int
etc but in terms of an iterator, what's the difference here between ++iter
and iter++
? (Bear in mind that I do know that both yield the same result here).
Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented.
Answer: Pre increment operator is used to increment variable value by 1 before assigning the value to the variable. Post increment operator is used to increment variable value by 1 after assigning the value to the variable.
Postfix increment operator means the expression is evaluated first using the original value of the variable and then the variable is incremented(increased). Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased).
Answer: Pre decrement operator is used to decrement variable value by 1 before assigning the value to the variable. Post decrement operator is used to decrement variable value by 1 after assigning the value to the variable.
++iter
is most likely to be faster but never slower than iter++
.
Implementing the post increment operator iter++
needs to generate an additional temporary(this temporary is returned back while the original iter
is incremented ++
) over implementing the post increment operator ++iter
, So unless the compiler can optimize(yes it can) the post increment, then ++iter
will most likely be faster than iter++
.
Given the above, It is always preferable to use ++iter
in the looping conditions.
The difference is they do not yield the same result, while this particular example will do the same regardless of the increment form used. The pre-increment form first increments the value, and then returns it; while the post-increment form increments the result but returns the value previous to incrementation. This is usually a no cost for fundamental types, but for things like iterators it requires creating a temporary value to hold the non-incremented value, in order to be later returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With