Many common array
manipulations use for statements
. For example, the following for
statement sets all the elements in row 2 of array a
in Fig. 7.19 to zero:
for ( size_t column = 0; column < 4; ++column )
a[ 2 ][ column ] = 0;
The for
statement varies only the second subscript (i.e., the column subscript). The preceding for
statement is equivalent to the following assignment statements:
a[ 2 ][ 0 ] = 0;
a[ 2 ][ 1 ] = 0;
a[ 2 ][ 2 ] = 0;
a[ 2 ][ 3 ] = 0;
The following nested counter-controlled for
statement determines the total of all the elements in array a
in Fig. 7.19:
total = 0;
for ( size_t row = 0; row < a.size(); ++row )
for ( size_t column = 0; column < a[ row ].size(); ++column )
total += a[ row ][ column ];
The for
statement totals the elements of the array
one row at a time. The outer for
statement begins by setting row
(i.e., the row subscript) to 0
, so the elements of row 0 may be totaled by the inner for
statement. The outer for
statement then increments row
to 1
, so the elements of row 1 can be totaled. Then, the outer for
statement increments row
to 2
, so the elements of row 2 can be totaled. When the nested for
statement terminates, total
contains the sum of all the array
elements. This nested loop can be implemented with range-based for statements as:
total = 0;
for ( auto row : a ) // for each row
for ( auto column : row ) // for each column in row
total += column;
13.58.197.26