Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept difference between pre and post increment operator for STL

Tags:

c++

stl

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).

like image 565
yapkm01 Avatar asked Sep 15 '11 19:09

yapkm01


People also ask

What is the difference between pre increment and post increment operators?

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.

What is difference between pre and post operator?

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.

What is the difference between post increment and post decrement operator?

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).

What is the difference between pre decrement operator and post decrement operator?

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.


2 Answers

++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.

like image 99
Alok Save Avatar answered Oct 19 '22 06:10

Alok Save


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.

like image 44
K-ballo Avatar answered Oct 19 '22 06:10

K-ballo