Ranged for loop with arrays of arrays

1
2
3
4
5
6
7
        int arr[4][5];

	for (int(&row)[5] : arr){
		for (int &column : row){

		}
	}

Why do we name it row instead column? int arr[row][column]
Wouldn't this be like
1
2
3
4
5
6
int arr[4][5];

	for (int(&column)[5] : arr){
		for (int &row: column){

		}

It just seems funny to me because we use row[5] which should be 4 if we meant row? Or did I read it wrong in C++ prime !?
You can of course call it whatever you want but if you use the convention array[rows][columns], then arr[1] gives you the second row, and when you do do row[3] you get the value of the fourth column of the row.
1
2
3
4
5
6
int m[3][4] =
{
  { 1,  2,  3,  4 },  // row 0
  { 5,  6,  7,  8 },  // row 1
  { 9, 10, 11, 12 }   // row 2
};

The array m has 3 rows and 4 columns.

If I want to access the element at the second row (row 1) and the third column (column 2), then I would write m[1][2].

If I want to access an entire row, I do it easily: m[1] → {5,6,7,8}.

This makes it difficult to access data by columns, but it proves to be less problematic than you would think. (There are numerous ways around it.)

Hope this helps.
Last edited on
Topic archived. No new replies allowed.