As we’ve shown, it’s common to process all the elements of an array
. The new C++11 range-based for statement allows you to do this without using a counter, thus avoiding the possibility of “stepping outside” the array
and eliminating the need for you to implement your own bounds checking.
Error-Prevention Tip 7.2
When processing all elements of an array, if you don’t need access to an array element’s subscript, use the range-based for statement.
The syntax of a range-based for
statement is:
for ( rangeVariableDeclaration : expression )
statement
where rangeVariableDeclaration has a type and an identifier (e.g., int item
), and expression is the array
through which to iterate. The type in the rangeVariableDeclaration must be consistent with the type of the array
’s elements. The identifier represents successive array
element values on successive iterations of the loop. You can use the range-based for
statement with most of the C++ Standard Library’s prebuilt data structures (commonly called containers), including classes array
and vector
.
Figure 7.13 uses the range-based for
to display an array
’s contents (lines 13–14 and 22–23) and to multiply each of the array
’s element values by 2 (lines 17–18).
1 // Fig. 7.13: fig07_13.cpp
2 // Using range-based for to multiply an array's elements by 2.
3 #include <iostream>
4 #include <array>
5 using namespace std;
6
7 int main()
8 {
9 array< int, 5 > items = { 1, 2, 3, 4, 5 };
10
11 // display items before modification
12 cout << "items before modification: ";
13 for ( int item : items )
14 cout << item << " ";
15
16 // multiply the elements of items by 2
17 for ( int &itemRef : items )
18 itemRef *= 2;
19
20 // display items after modification
21 cout << "
items after modification: ";
22 for ( int item : items )
23 cout << item << " ";
24
25 cout << endl;
26 } // end main
items before modification: 1 2 3 4 5
items after modification: 2 4 6 8 10