tags:

views:

150

answers:

3

I see somewhere it metions:

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.

+17  A: 

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.

Ben Voigt
+4  A: 

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 !=.

Brian Neal
+3  A: 

The former only works for iterators that support operator <, which not all iterators do.

Chris Dodd