首页 > 解决方案 > 输入后不执行在排序矩阵中搜索整数的代码

问题描述

以下代码接受输入,但不执行或返回任何输出。它将一个矩阵及其大小和一个要搜索的整数作为输入。我无法理解这里的问题。

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

标签: c++

解决方案


在找到数字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;
}

推荐阅读