我对使用多维数组不是很熟悉,在这里我试图查看2d数组中是否存在元素,如果存在,我需要某种指示。

// initialize an array 3x3
int matrix[3][3];
bool found = false;
// The matrix will be loaded with all 0 values, let's assume this has been done.

// Check if there are any 0's left in the matrix...

for(int x = 0; x < 3; x++){
    for(int y = 0; y < 3; y++){
        if(matrix[x][y] == 0){
           break; // << HERE I want to exit the entire loop.
        }else{
            continue; // Continue looping till you find a 0, if none found then break out and make: found = true;
        }
    }
}

最佳答案

控制标志将很有用:

bool found = false;
for (unsigned int row = 0; (!found) && (row < MAX_ROWS); ++ row)
{
  for (unsigned int column = 0; (!found) && (column < MAX_COLUMNS); ++ column)
  {
    if (matrix[row, column] == search_value)
    {
       found = true;
    }
  }
}


编辑1:
如果要保留rowcolumn值,则需要在每个循环中均break

bool found = false;
for (unsigned int row = 0; (!found) && (row < MAX_ROWS); ++ row)
{
  for (unsigned int column = 0; (!found) && (column < MAX_COLUMNS); ++ column)
  {
    if (matrix[row, column] == search_value)
    {
       found = true;
       break;
    }
  }
  if (found)
  {
    break;
  }
}

关于c++ - 检查2d数组中是否存在元素,如果为true,则返回某些内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27303390/

10-11 22:37
查看更多