zondag 17 juni 2007

Two dimensional arrays

C++ does not provide a special two-dimensional array type. Instead you create an array for which each element is itself an array.
For example, suppose you want to store the maximum temperature data for five citys over a 4-year period. In that case, you can declare an array as follows:

int maxtemps[4][5];

This declaration means that maxtemps is an array with 4 elements. Each of these elements is an array of 5 integers.
You can think of maxtemps array as representing 4 rows of 5 temperature values each.

The expression maxtemps[0] is the first element of the maxtemps array.
The first element of the maxtemps[0] array is maxtemps[0][0], and this element is an single int. Thus you need to use two subscripts to access the int elements.
You can think of the first subscript as representing the row, and the second subscript as representing the column.

Suppose you want to print all the array contents. In that case, you can use one for loop to change the rows, and a second, nested for loop to change the collumns:

for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 5; ++col)
cout << maxtemps[row][col] << "\t";
cout << endl;
}

For each value of row, the inner for loop cycles through all the col values.
This example prints a tab character (\t in C++ escape character notation) after each value and a newline character after each complete row.

Initializing a Two-Dimensional Array
When you create a two-dimensional array, you have the option of initializing each element.

The initialization consists of a comma-separated series of one-dimensional initializations, all enclosed in a set of braces:

int maxtemps[4][5] = // 2-D array
{
{94, 98, 87, 103, 101}, // values for maxtemps[0]
{98, 99, 91, 107, 105}, // values for maxtemps[1]
{93, 91, 90, 101, 104}, // values for maxtemps[2]
{95, 100, 88, 105, 103} // values for maxtemps[3]
};

Geen opmerkingen: