I've seen both of these two for statements:
for(i=0;i<10;i++) for(i=0;i!=10;i++)
I know they all stop when i reaches 10
, but it seems better to use the second one (I heard). What is the different?I also want to know when use iterator to access member of a vector, what is the difference between iterator condition < vec.end()
and != vec.end()
All three expressions in the head of the for loop are optional. Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop. You can also omit all three blocks.
Traditional for-loops Another form was popularized by the C programming language. It requires 3 parts: the initialization (loop variant), the condition, and the advancement to the next iteration.
All these components are optional. In fact, to write an infinite loop, you omit all three expressions: for ( ; ; ) { //infinite loop ... }
What Does For Loop Mean? For loop is a programming language conditional iterative statement which is used to check for certain conditions and then repeatedly execute a block of code as long as those conditions are met.
for(i = start; i != end; ++i)
This is the "standard" iterator loop. It has the advantage that it works with both pointers and standard library iterators (you can't rely on iterators having operator<
defined).
for(i = start; i < end; ++i)
This won't work with standard library iterators (unless they have operator<
defined), but it does have the advantage that if you go past end
for some reason, it will still stop, so it's slightly safer. I was taught to use this when iterating over integers, but I don't know if it's actually considered "best practice".
The way I generally write these is to prefer <
.
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