2d array with range-based for statement

I am trying to set each of the element to zero in the 2 dimension array with a nested range-based for statement. I am missing something because it does not set all of them to zero.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <array>
using namespace std;

int main(){
  const size_t row{2};
  const size_t column{3};
  
  array<array<int,column>,row>array1{1,2,3,4,5,6};
  
  for(auto& r :array1){
      for(auto& c : r){
          r[c] = 0;
      }
  }

  for(size_t rowA{0}; rowA<array1.size(); rowA++){
    for(size_t columnA{0}; columnA<array1[rowA].size();columnA++){
        cout << array1[rowA][columnA] << " ";
  }
  cout << endl;
  }
  
  
}
1
2
3
  for (auto& row: array1)
      for(auto& element: row)
          element = 0;

You're not using the range based loop correctly. "c" is an element of the "column" not an index value.

Your loop should look more like:

1
2
3
for(auto& row : array1)
    for(auto& col : row)
        c = 0;

Apparent doublepost. Previous thread: http://www.cplusplus.com/forum/beginner/275598/
Keskiverto. That was a question about specific element initalization to zero. This question is about to set ALL elements to zero with range-based for statement. Sorry I am a beginner for me it is not the same question.
Thank you for the answers.
Well with the code you posted you really should be using initialization not assignment to set all the elements to zero.

Topic archived. No new replies allowed.