Dingle
Dingle

Reputation: 2452

C++ iterator in for loop pitfalls?

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

Answers (3)

Chris Dodd
Chris Dodd

Reputation: 126223

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

Upvotes: 5

Brian Neal
Brian Neal

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

Ben Voigt
Ben Voigt

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

Related Questions