检查 2D 数组中是否存在元素,如果为 true,则返回一些内容
Check if an element exists in a 2d array and return something if true
我对使用多维数组不是很熟悉,在这里我试图查看元素是否存在于 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:
如果要保留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";
相关文章:
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- C++如果使用 lambda 表达式的语句返回 true,但输出来自 false,为什么
- 测试用例状态为失败,但返回的值为 true
- MFC 的 OnInit() 函数中的返回 true 和返回 false 有什么区别
- 我正在尝试创建一个布尔函数,该函数计算字符并在字符为"()*-+"时返回 true
- 创建一个函数,如果元素在unordered_set中,则返回 true,如何处理模板
- QTimer isActive 返回 true,但 remainingTime 返回 -1
- 为什么在 IsValid(Object) 返回 true 后不能安全地使用 Object?
- 计算 <Classtype*> 向量中所有项的布尔值的最有效方法,如果全部为真则返回 true
- QDir mkpath 返回 true,但未创建目录
- std::is_array 当它应该返回 false 时返回 true
- 尝试创建一个评估字符的bool函数,如果字母数字为字母,则返回true
- 我想返回 True/False 关于值是否在一组值中
- 为什么我的布尔函数返回 true 会导致读取访问冲突?
- ifstream::is_open 返回 true,即使该位置不存在文件也是如此
- 是否有内置函数返回" the number of true value in a boolean vector "?
- 为什么包含指针的条件总是返回 true?
- 对于 ((无符号整数)0-1)返回 true>0
- 为什么#ifndef __func__返回true
- 我的bool函数一直返回true,我不知道为什么