Assigning value to 2d array

What statement should I use to set the values in the first row and the second column to zero in this 2-by-3 array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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(size_t row{0}; row<array1.size(); row++){
    for(size_t column{0}; column<array1[row].size();column++){
        cout << array1[row][column] << " ";
    }
    cout << endl;
  }
}
Last edited on
medosz wrote:
... to set the values in the first row and the second column to zero
array1[0][1] = 0;
First a note: your row masks row. Same for column(s).
Confusing? Indeed.
Line 6 declares variable row. It is used on line 9. It continues to exist to line 17.
Line 11 declares variable row. It is used on lines 12 and 13. It continues to exist to line 16.
This latter variable exists in the scope of the loop. You cannot refer to the other (const) row within the loop.


You want set values to second column?
Simply iterate over rows:
1
2
3
for ( auto& r : array1 ) {
  r[1] = 0; // assumes that each row has at least two elements
}

Set values of row x?
Iterate over columns of that row:
1
2
3
for ( size_t c{0}; c < array1[x].size(); ++c ) {
  array1[x][c] = 0;
}


Then again, you know what you will need:
array<array<int,column>,row> array1 {0,0,0,4,0,6};
Last edited on
Hello medosz,

To go along with what keskiverto has said consider this:

6
7
constexpr size_t ROWS{2};
constexpr size_t COLS{3};

The capital letters help to denote that the variable is a constant. The name is still your choice. But later say in line 9 it would make the code much less confusing.

Lines 9, 11 and 12 could use some spaces to make the code easier to read. but if you are writing the code for the compiler then it is OK and there is still to much white space for the compiler.

Andy
Registered users can post here. Sign in or register to post.