Search code examples
c++for-loopiterator

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?


Solution

  • 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.