【问题标题】:C++: Help me finding a bug - 2D array search -C++:帮我找到一个错误 - 2D 数组搜索 -
【发布时间】:2014-06-01 23:06:35
【问题描述】:

我的程序要求输入数字并将它们放在二维数组中。 然后它会询问一个数字并执行搜索,然后在二维数组中打印该数字的位置。

搜索功能有一个错误,将 1 添加到预期的行位置。通过将 1 减去“行”变量来“修复”它,但它是 ovb 不可接受的。

目前对此感到有点愚蠢,将不胜感激。

#include <iostream>
using namespace std;

#define R 3
#define C 2    

typedef int matrix[R][C];

void input(matrix m)
{
int i, j;
i = j = 0;

    for(i = 0; i< R; i++)
    {
        for(j = 0; j < C; j++)
        { 
            cout << "Row " << i << " Column " << j << ": ";
            cin >> m[i][j];
        }
    }
}

void search(int x, matrix m, int& row, int& column)
{
int r, c;
bool OK;
OK = false;
r = 0;

    while((!OK) && (r < R)) 
    {
        c = 0;
        while((!OK) && (c < C))
        {
            if(m[r][c] == x)
                OK = true;
            else
                c++;
        }
        r++;    
    }

    column = c;
    row = r-1;  //LOL
}



int main()
{
    matrix mat;
    int number;
    int row;
    int column;

    input(mat);

    cout << "Which number are you looking for?: ";
    cin >> number;
    search(number, mat, row, column);
    cout << endl << "Row " << row << " Column: " << column;

    fflush stdin;
    getchar();
    return 0;
}

【问题讨论】:

    标签: c++ arrays search


    【解决方案1】:

    你应该通过引用input来传递矩阵:

    void input(matrix& m)
    

    否则你不会填充矩阵。

    我也建议改变这个:

    #define R 3
    #define C 2
    

    到:

    const std::size_t R = 3;
    const std::size_t C = 2;
    

    最后我建议你看看std::arraystd::search

    【讨论】:

    • 我的理解是默认情况下数组是通过引用传递的。所以不需要加&。有错吗?
    • @MV_81,除非您输入&amp;,否则不会通过引用传递任何内容。数组有时会衰减为指针,但指针不是任何形状或形式的引用。
    • 是的! Ty,试图将其标记为已解决,但我没有找到按钮。
    【解决方案2】:

    当找到值时,代码必须确保r 不递增(参见下面的代码,if 语句用于检查是否找到了值)。此外,row 也不是在搜索功能结束时从 r 分配的。

    void search(int x, matrix m, int& row, int& column)
    {
        int r, c;
        bool OK = false;
        r = 0;
    
        while((!OK) && (r < R))
        {
            c = 0;
            while((!OK) && (c < C))
            {
                if(m[r][c] == x)
                    OK = true;
                else
                    c++;
            }
            if (!OK)
                r++;
        }    
        column = c;
        row = r;
    }
    

    【讨论】:

    • 老兄!如果 (!OK) r++;修复!不需要 break 语句。你确定有需要吗?
    • 很高兴听到它的工作。你是对的 - 不需要 break 因为 c++ 语句在 else 子句中。
    • ps 你应该接受最有用的答案 - 在这里完成了 :)
    【解决方案3】:

    如果OK 为真,最简单的解决方案是不增加r

    您还可以将 while 循环替换为它们的 for 等效项。

    for(r = 0; !OK && r < R; r += 1)
    {
        for(c = 0; !OK && c < C; c += 1)
        {
            OK = (m[r][c] == x);
        }
    }
    

    如果OK 为真,这将防止r 递增。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      相关资源
      最近更新 更多