[英]Check if an element exists in a 2d array and return something if true
我對使用多維數組並不是很熟悉,在這里我試圖查看一個元素是否存在於二維數組中,如果存在,我想要某種指示。
// 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:
如果你想保留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;
}
}
嘗試這個 :-
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.