警告:控制可能达到无效功能的结束?什么时候上课

问题描述 投票:1回答:2

我有这个函数,它将搜索与向量中的借用ID匹配的ID,然后返回具有匹配ID的借用者。但是我一直收到这个警告?

Borrower getborrowerbyID(string ID)  
{
    for(int i =0; i<Borrowlist.size();i++)
    {
        if(Borrowlist[i].getID()==ID)
        {
            return Borrowlist[i];

        }
    }
}
c++ class return
2个回答
0
投票

我将返回成功状态,并通过函数参数传递匹配,如下所示:

bool getborrowerbyID(string ID, Borrower& refBorrower)  
{
    for(int i =0; i<Borrowlist.size();i++)
    {
        if(Borrowlist[i].getID()==ID)
        {
            refBorrower = Borrowlist[i];
            return true; // signall sucess match found
        }
    }
    return false; // signal falure, ie. no match
}

现在您可以测试同一时间是否匹配:

if(getborrowerbyID(ID, refBorrower))
{
      // ok
}
else
{
      // handle error
}

0
投票

当找不到搜索ID时,您确实没有返回。你可能会改为:

Borrower& getBorrowerByID(const std::string& ID)  
{
    auto it = std::find_if(Borrowlist.begin(), Borrowlist.end(),
                           [&](const Borrower& borrower){ return borrower.getID() == ID; });

    if (it == Borrowlist.end()) {
        throw std::runtime_error("Not found");
    }
    return *it;
}

或返回指针:

Borrower* getBorrowerByID(const std::string& ID)  
{
    auto it = std::find_if(Borrowlist.begin(), Borrowlist.end(),
                           [&](const Borrower& borrower){ return borrower.getID() == ID; });

    if (it == Borrowlist.end()) {
        return nullptr; // Not found
    }
    return std::addressof(*it); // or &*it assuming no evil overload of unary operator& 
}
© www.soinside.com 2019 - 2024. All rights reserved.