Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a range for loop be used instead of iterators on a vector?

Given a vector, vc, one can iterate through the vector with a range for:

for (auto c : vc)
    std::cout << c;

Or with an iterator:

for (auto it = vc.cbegin(); it != vc.cend(); ++it)
    std::cout << *it;

Is there a functional reason to use one method over the other, or is this merely a matter of style?

like image 830
Jesse Avatar asked Feb 15 '16 19:02

Jesse


People also ask

Do range based for loops use iterators?

Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable.

Are range based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).

Can we use iterator in vector?

No. It is not a bad practice, but the following approach renders your code certain flexibility. Usually, pre-C++11 the code for iterating over container elements uses iterators, something like: std::vector<int>::iterator it = vector.


2 Answers

From the performance point of view there isn't really a difference. As Bjarne Stroustrup writes in his book the C++ Programming language 4th edition:

The simplest loop is a range- for -statement; it simply gives the programmer access to each element of a range.

As a fan of the KISS principle I tend to prefer simpler constructs over more complex ones. However, it really boils down to what you want to achieve. From the same book Bjarne reveals why a range-for loop is designed to be simple:

Note that a range- for loop is a deliberately simple construct. For example, using it you can’t touch two elements at the same time and can’t effectively traverse two ranges simultaneously. For that we need a general for-statement.

Consequently, there are contexts that you can't use a range-for loop and you have to reside to the classical for-statement.

Bottom line use range-for loop when ever possible because is simpler and more readable.

like image 86
101010 Avatar answered Sep 21 '22 14:09

101010


It is more or less a matter of style, but consider it this way; range-for loops are more concise than explicit iterator usage. The less code you write, the less places where things can go wrong.

like image 20
JesseTG Avatar answered Sep 21 '22 14:09

JesseTG