Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterator in for loop pitfalls?

Tags:

c++

iterator

stl

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.

like image 688
Dingle Avatar asked Jun 22 '10 02:06

Dingle


1 Answers

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.

like image 193
Ben Voigt Avatar answered Oct 05 '22 23:10

Ben Voigt