I've been reading the "Starting Out With C++" book and I have a question. Here is the paragraph:
"The Range-Based for Loop versus the Regular for Loop
The range-based for loop can be used in any situation where you need to
step through the elements of an array, and you do not need to use the
element subscripts. It will not work, however, in situations where you
need the element subscript for some purpose. In those situations, you need
to use the regular for loop."
My question is when will I need to use element subscripts and why won't a "Range-Based for Loop" work with subscripts?
An example of needing the subscript is when you're comparing an element of an array with the next element. e.g. if (val[i] < val[i+1]).
why won't a "Range-Based for Loop" work with subscripts?
The code inside a range-based for loop doesn't have access to the element's subscript. It may be better to think of it as "a range based for loop doesn't used an array's subscript" rather than thinking that it won't work with the subscript.
Everytime when you need to find index of element (or iterator, as it does not work with iterators either), or need to have free access to next/precious/etc. values inside the loop.
why won't a "Range-Based for Loop" work with subscripts?
Because it is by definition operates on container valuies without prociding access to their indexes(which might not exist)/iterators(which might be input iterators).
So comparing and testing arrays will need a subscript and will require a "Regular for Loop" and a "Ranged-Based for Loop" is best used to display the contents in a single array? @dhayden @MiiNiPaa
Range-based loop is used when all you care is values, not their position, not their neighbours, etc. For example finding sum of all array elements, copying all negative numbers to another array, displaying only those solutions which satisfies other requirements...
Regular loop should be used when range-based one is not enough.
Additionally you should study what <algorithm> header has to offer. If covers about 75% of common loop usage.