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?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With