Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an iterator-based for-loop better than an index-based loop?

This may seem like an odd question but I was talking to a friend today who was ranting about today's C++ programmers and how they just don't do things quite right. He said his main pet peeve was the abuse of iterating, in code like this:

for(int i = 0; i<((int) someVector.size()); ++i){
    //Something here
}

instead of the more traditional

vector::iterator i;
for(i = someVector.begin(); i!=someVector.end(); ++i){
    //Something here
}

While I understand both methods, is there any particular reason why the second is superior to the first? Is it performance? Or some other factor?

like image 984
Daniel Gratzer Avatar asked Dec 06 '25 08:12

Daniel Gratzer


2 Answers

Neither one of those is good style.

The first has a useless and dangerous cast.

The second allows the iteration variable to leak outside the loop's scope, and doesn't use an equality test, and uses a post-increment on an iterator, which makes a useless copy.

Better is:

using std::begin, std::end;
for( auto it = begin(container), end_it = end(container); it != end_it; ++it )

This works with any STL container, arrays, and any container you provide with begin and end helper functions.

like image 94
Ben Voigt Avatar answered Dec 09 '25 00:12

Ben Voigt


For a vector, there is little difference between the two. However, if you wanted to iterate over a data structure such as a set, that doesn't have random access at all, then the second option using iterators would be the only sensible choice.

The C++ standard library goes to great effort to make the "iterator" interface as consistent as possible over many different types of containers.

like image 35
Greg Hewgill Avatar answered Dec 09 '25 00:12

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!