operator<
is only supported for random access iterators. std::vector::iterator
is a random access iterator, so both i != vec.end()
and i < vec.end()
are supported and valid and make no difference in your example.
If you had a container that does not support random access iterators (e.g. std::list
), i < list.end()
would not compile.
The general recommendation is to use postfix increment only when it is necessary though because it may create an unnecessary copy when the iterator is non-trivial, so ++i
is cleaner and may be faster.
Also, if the loop calls a function whose definition is not available in this translation unit vec.end()
is going to be reloaded from memory on each loop iteration, which might cause an unnecessary cache miss. You can avoid that reload by saving the value into a local variable, so that the compiler is certain that the local variable is inaccessible to any other function:
for(vector<int>::iterator i = vec.begin(), j = vec.end(); i < j; ++i)
// ...
Even better, you may like to use range-for loops that avoid these performance pitfalls for you:
for(auto const& elem : vec)
// ...