线性搜索类对象的数组

时间:2013-01-22 21:05:18

标签: c++ arrays search linear

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

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

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() ;

}

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 ;
}

答案 2 :(得分: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 ;
}

[...]