IN
for ( auto it = s.begin(); it != s.end(), ++it )
s.begin() is called only once.
s.end() and operator++() (for ++it ) are called at each iteration of the loop.
Can the compiler optimize it?
The compiler may optimize the s.end() call depending on the compiler, implementation, and level of optimization. I will be surprised if he can optimize the operator++() call.
Are current compilers smart enough for this?
I can not answer this question.
Or am I better off using something like the following:
for (auto it = s.begin(), auto end = s.end(); it != end; ++it) {}
It will not hurt. However, this can be a problem if s modified in a loop. If s not changed in the loop, I would recommend using this approach.
source share