Skip to main content

Section 14.5 Single Dimension Traversals

It is also possible to traverse just one dimension of a multidimensional set of data. Say we just want to print out the third row of a table of data. This only requires traversing in one dimension - side to side through a single row. The list of elements we need to visit looks like:
matrix.at(2).at(0)
matrix.at(2).at(1)
matrix.at(2).at(2)
matrix.at(2).at(3)
Figure 14.5.1. The third row of data in a 3x4 matrix.
The row of everything we are trying to access is 2. This means we can use a set value for the row index. Which means we do not need a loop that iterates through the various rows. Instead, we will have a single loop that traverses the columns of that row. The code looks like this:
Listing 14.5.2.
Note that even though we are only using a single loop to traverse one dimension, we still have to specify both a row and column to access a single int value in the table.

Insight 14.5.1.

gridName.size() returns the number of rows when gridName is a two-dimensional vector.
To get the number of columns in a particular row, use gridName.at(rowIndex).size(). If all the rows have the same number of columns, you can use gridName.at(0).size().

Checkpoint 14.5.1.

You have attempted of activities on this page.