c++ - 输入后不执行在排序矩阵中搜索整数的代码
问题描述
以下代码接受输入,但不执行或返回任何输出。它将一个矩阵及其大小和一个要搜索的整数作为输入。我无法理解这里的问题。
#include<iostream>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int a[n][m];
int t;
cin >> t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int r = 0, c = m - 1;
bool found = false;
while (r < n && c >= 0)
{
if (a[r][c] == t)
{
found = true;
}
else if (a[r][c] < t)
{
r++;
}
else
{
c--;
}
}
if(found)
{
cout << "found";
}
else
{
cout << "not found";
}
return 0;
}
解决方案
在找到数字break
后写下你想要的。找到数字后,您不会退出循环。
#include<iostream>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int a[n][m];
int t;
cin >> t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int r = 0, c = m - 1;
bool found = false;
while (r < n && c >= 0)
{
if (a[r][c] == t)
{
found = true;
break;
// ^^^^^^^
}
else if (a[r][c] < t)
{
r++;
}
else
{
c--;
}
}
if(found)
{
cout << "found";
}
else
{
cout << "not found";
}
return 0;
}
UPDATE 1.0
: 更新了考虑可变长度数组注释的代码。在 C++ 中使用vector
以达到相同的目的。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
// Using vector of vectors instead of 2-D array
vector< vector <int> > a(n);
for(int i = 0; i < n; i++){
a[i] = vector<int> (m);
}
int t;
cin >> t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int r = 0, c = m - 1;
bool found = false;
while (r < n && c >= 0)
{
if (a[r][c] == t)
{
found = true;
break;
// ^^^^^^^
}
else if (a[r][c] < t)
{
r++;
}
else
{
c--;
}
}
if(found)
{
cout << "found";
}
else
{
cout << "not found";
}
return 0;
}
推荐阅读
- netlogo - NetLogo - 将海龟移动到最近的海龟
- mysql - 识别NodeJS mysql中的主键
- angular-reactive-forms - 为多个字段订阅 valueChanges 导致反应形式 angular 2 的性能问题
- go - 无法在多个分配中将 *pubsub.Topic 分配给 mytopic(自定义类型)
- seaborn - 如何在某些轴上更改 seaborn heatmap tick_params 文本方向并使其完全适合图片
- javascript - 从 spotify 获取音频 - 加入音频块
- python - 创建一个“for”循环来加密python中的多个文件
- javascript - 将 HTML 解析为 XML 后,值无法正确显示
- c++ - '条件总是错误'的不正确的clion警告
- javascript - 尝试在 HTML 页面的 js 脚本中使用 window.onLoad() 时未捕获的 TypeError