Help understanding 2D STL array

I'm trying to understand this. The way I see it, there is an array of arrays.
The first for loop loops through the the arrays rows, and the second the columns.

What is the "rows". I haven't defined any constant yet it still works. I realize I can change it to anything, I'm just unsure what is happening here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  array<array<int, collumns>, row>MDA;

int main()
{
	for (auto &rows: MDA)
	{
		for (auto &element : rows)
		{
			
				element = true;

		}
	}
}
Last edited on
> there is an array of arrays.

Yes.

> The first for loop loops through the the arrays rows, and the second the columns.

Yes.

What is the "rows".

rows is the name of the variable; its type is 'reference to array<int, collumns>'
The type is deduced. See: http://www.stroustrup.com/C++11FAQ.html#auto
The loop is a range based loop. See: http://www.stroustrup.com/C++11FAQ.html#for
should it be bool instead of int?
Take a look at this example because yours has some naming inconsistencies which make it more difficult to reason about:
1
2
3
4
5
6
7
8
9
10
static constexpr std::size_t n_rows{5}, n_columns{10};
std::array<std::array<int, n_columns>, n_rows> mda; 
  
// row is a lvalue-reference to a particular row
for (auto &row: mda) {
  // elt is a lvalue-reference to a particular ELemenT of that row
  for (auto &elt: row) { 
    elt = 42; 
  }
}


In your own example, rows is declared in the outer loop, and binds to each row of MDA in order.
Last edited on
Thanks guys,

How would I use a standard for loop instead of a range based for loop?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17


const size_t collumns = 6;
const size_t row = 7;
array<array<int, row>, collumns >MDA;

int main()
{
	for (int i = 0; i < collumns; ++i)
	{
		for (int x = 0; x < row; ++x)
		{
			MDA[x] = x//not correct;
		}
	}

MDA[i][x] = x;
Topic archived. No new replies allowed.