Reputation: 2452
I see somewhere it mentions:
for ( itr = files.begin(); itr < files.end(); ++itr ) // WRONG
for ( itr = files.begin(); itr != files.end(); ++itr ) // ok
Why is the first expression wrong? I always used the first expression, and didn't have any problems.
Upvotes: 9
Views: 610
Reputation: 126223
The former only works for iterators that support operator <
, which not all iterators do.
Upvotes: 5
Reputation: 32389
There are different types of iterators. Only random-access iterators support the <
operator. Other types of iterators (bidirectional, input, output, and forward) do not. But all iterators support the ==
and !=
operators. Therefore your code will work with all types of iterators if you use !=
.
Upvotes: 7
Reputation: 283674
Ordering comparisons such as <
, >
, <=
, >=
will work for random-access iterators, but many other iterators (such as bidirectional iterators on linked lists) only support equality testing (==
and !=
). By using !=
you can later replace the container without needing to change as much code, and this is especially important for template code which needs to work with many different container types.
Upvotes: 21