简体   繁体   English

为什么搜索失败?

[英]Why does this searching fail?

I have just learnt C++ for a very short time, and in an assignment I am trying to find a particular target in a 2-dimensional array as follows: 我刚刚学习了C ++很短的时间,在一项作业中,我试图在二维数组中找到特定的目标,如下所示:

bool simsearch(int array[22][22], int target, int n){
    bool result = 0;
    for (int a = 1; a < n + 1; a++){
        for (int b = 1; b < n + 1; b++){
            if (array[a][b] == target)
                result = 1;
                break;
        }
    }
    return result;
}

and use it like: 并像这样使用它:

if(simsearch(substitute, 6, size) == 0){
        cout << "**Warning**" << '\n';
    }

But, the warning output is always there even if the target is in the array. 但是,即使目标位于数组中,警告输出也始终存在。 What is the underlying problem in the code? 代码中的根本问题是什么?

Thanks! 谢谢!

Indices of arrays start from 0 and if an array has n elements then the highest index is n-1. 数组的索引从0开始,如果数组有n个元素,则最高索引为n-1。

Rewrite the function the following way 通过以下方式重写函数

bool simsearch( const int array[22][22], int target, int n )
{
    bool found = false;

    for ( int i = 0; i < n && !found; i++ )
    {
        for ( int j = 0; j < n && !found; j++ )
        {
            if ( array[i][j] == target ) found = true;
        }
    }

    return found;
}

Or 要么

bool simsearch( const int array[22][22], int target, int n )
{
    bool found = false;

    for ( int i = 0; i < n && !found; i++ )
    {
        int j = 0;

        while ( j < n && array[i][j] != target ) j++;

        found = j != n; 
    }

    return found;
}

I hope that the argument for n is always equal to 22.:) 我希望n的参数始终等于22::)

Another approach is the following 另一种方法是以下

template <typename T, size_t M, size_t N>

bool simsearch( const T ( &a )[M][N], const T &value )
{
    bool found = false;

    for ( size_t i = 0; i < M && !found; i++ )
    {
        size_t j = 0;

        while ( j < N && !( a[i][j] == value ) ) ++j;

        found = j != N;
    }

    return found;
}
bool simsearch(int array[22][22], int target, int n){
    bool result = 0;
    for (int a = 0; a < n ; a++){
        for (int b = 0; b < n; b++){
            if (array[a][b] == target){
                result = 1;
                break;
            }
        }
        if(result) break;
    }
    return result;
}

This should work. 这应该工作。 Use brackets and conditions properly 正确使用括号和条件

There are two things to notice over here:- 这里有两件事要注意:

for (int a = 1; a < n + 1; a++)

If n represents size here ( which seems from call to this function) then this you need to change. 如果n在这里表示大小(从对该函数的调用看来),则需要进行更改。 Array of size 10 must be indexed from 0 to 9. 大小为10的数组的索引必须从0到9。

Second thing rather than returning integer 第二件事,而不是返回整数

return result;

you can return true OR false. 您可以返回true或false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM