【问题标题】:Check if an element exists in a 2d array and return something if true检查二维数组中是否存在元素,如果为真则返回
【发布时间】:2014-12-04 20:27:12
【问题描述】:

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

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

【问题讨论】:

  • 使用 found 变量。删除continue;没有你的循环就不会做任何其他事情。
  • 你需要在 break 之前设置一些标志(例如,布尔变量)。然后,检查内部循环外部的标志,并在必要时再次中断。这将打破两个循环。你不需要那个 continue 语句。
  • 把它变成一个函数,找到后直接返回,代码会更简洁。

标签: c++ arrays loops matrix


【解决方案1】:

控制标志会很有用:

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:
如果您想保留 row 和 column 值,那么您需要在每个循环之外使用 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;
  }
}

【讨论】:

    【解决方案2】:

    试试这个:-

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

    【讨论】:

    • 为什么需要continue 语句?
    • 这有很大的问题,如果数组中没有任何零,它将不会返回任何内容。还是我错了?
    • 你为什么使用c作为标志而found变量作为标志?
    • 您可以使用if (found) cout &lt;&lt; "0 exists in the matrix\n"; 进行简化,无需c 变量。
    • 如果x == 1 和found == true,你的外循环将再次迭代。
    猜你喜欢
    • 2020-01-13
    • 2017-09-17
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多