简体   繁体   English

检查元素是否存在于二维数组中,如果为真则返回某些内容

[英]Check if an element exists in a 2d array and return something if true

I'm not all that familiar with using multidimensional arrays and here I'm trying to see if an element exists in a 2d array and if it does, I want some sort of indication.我对使用多维数组并不是很熟悉,在这里我试图查看一个元素是否存在于二维数组中,如果存在,我想要某种指示。

// 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;
        }
    }
}

A control flag will be useful:控制标志将很有用:

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;
    }
  }
}

Edit 1:编辑1:
If you want to preserve the row and column values then you need to break out of each loop:如果你想保留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;
  }
}

Try this :-尝试这个 :-

int matrix[3][3];
bool found = false;


for(int x = 0; x < 3 && found == false; x++)
  {
    for(int y = 0; y < 3; y++)
     {
       if(matrix[x][y] == 0)
       {
          found = true;
          break; 
       }
     }
 }
if (found)
 cout<<"0 exists in the matrix";
else
 cout<<"0 doesn't exist in the matrix";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM