1

我设置了一个线性搜索算法来搜索它工作的类对象数组,但输出不匹配,当我在数组中搜索特定名称时,找到数组中的第一个和第三个值,但第二个值是未找到。

以下是我的代码,感谢您的帮助。

int linsearch(string val)
{
    for (int j=0; j <= 3; j++)
    {
        if  (player[j].getLastName()==val)
         return j ;         
    }
        return 1 ;
}   


void showinfo()
{
    string search;
    int found ;


    cout << "Please Enter The Player's Last Name : " ;
    cin >> search ;

    found=linsearch(search);

    if (found==1)
    {
        cout << "\n There is no player called " << search ;
    }
    else
    {
        cout << "\n First Name : " << player[found].getFirstName() << "\n" << "Last Name : " << player[found].getLastName() <<
            "\n" << "Age : " << player[found].getAge() << "\n" << "Current Team : " << player[found].getCurrentTeam() << 
            "\n" << "Position : " << player[found].getPosition() << "\n" << "Status :  " << player[found].getStatus()  << "\n\n";
    }

    cin.get() ;

    menu() ;

}
4

3 回答 3

6

因为您将第二个元素的索引用作“未找到”代码:

int linsearch(string val)
{
    for (int j=0; j <= 3; j++)
    {
        if  (player[j].getLastName()==val)
         return j ;         
    }
        return 1 ;
}   

您应该返回一些不能作为索引的东西,例如-1. 或者更好的是,使用std::find_if

于 2013-01-22T21:07:56.653 回答
2

第二个元素的索引与标记“未找到”条件的值相同。

使用无效索引-1来标记“未找到”条件:

int linsearch(string val)
{
    for (int j=0; j <= 3; j++)
    {
        if  (player[j].getLastName()==val)
         return j ;         
    }

    return -1;
}

然后-1在调用函数中检查:

if (found==-1)
{
    cout << "\n There is no player called " << search ;
}
于 2013-01-22T21:08:23.707 回答
0

做这样的事情......如果找不到,则返回任何其他整数,如'-1'

int linsearch(string val)
{
for (int j=0; j <= 3; j++)
{
    if  (player[j].getLastName()==val)
     return j ;         
}
    return -1 ;
} 


void showinfo()
{
string search;
int found ;


cout << "Please Enter The Player's Last Name : " ;
cin >> search ;

found=linsearch(search);

if (found == -1)
{
    cout << "\n There is no player called " << search ;
}

[...]
于 2013-01-22T21:11:28.863 回答