user2201112 user2201112 - 1 month ago 16
C++ Question

How to iterate through a 2d vector?

I have a 2d vector of size 7*7 named table.

All of the values are 0 except for 2 of them.

When I run the following program, I am assuming I enter an infinite loop because nothing outputs to the screen and I have to press Ctrl+C to cancel in the terminal.

Currently I have this, which is giving me the error

for(x=0; x = 6 ; x++){
for(y=0; y = 6 ; y++){
if (table.at(x).at(y) != 0)
cout << "Yes." << endl;
}
}


I am not seeing why it doesn't go through each value of the table, in the order (0,0) then (0,1) then (0,2) ... (1,) (1,1) (1,2) ... etc until it goes through all them.

Answer

replace = with <=

for(x=0; x <= 6 ; x++){
  for(y=0; y <= 6 ; y++){
    if (table.at(x).at(y) != 0)
      cout << "Yes." << endl;
    else
      cout << "No." << endl;  
  }
}
Comments