1

i have this function that will search an ID that match the borrowed ID in a vector and then will return the borrower with the matching ID. However i keep getting this warning?

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

        }
    }
}
ZAX9732
  • 85
  • 6
  • 4
    What happens if there are no matches inside `Borrowlist`? The `return` will never get called and the function will drop out of the loop at the end. You need to find some way of signalling to the calling code that a match hasn't been found, and return that. – Steve Apr 08 '19 at 08:11
  • Incidentally, if you're just searching inside a `vector` for a match, there are methods inside the STL that will do that for you. – Steve Apr 08 '19 at 08:13
  • As Steve pointed out, what happens if no ID is found? You endup at the end of the function with no return statement. Then what should the function return? Also, check this out [In C++ check if std::vector contains a certain value](https://stackoverflow.com/questions/6277646/in-c-check-if-stdvectorstring-contains-a-certain-value) – Duck Dodgers Apr 08 '19 at 08:26
  • Use some `throw` at last statement. – Jarod42 Apr 08 '19 at 10:03

2 Answers2

0

I would return sucess status instead and pass a match via function argument like this:

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
}

Now you can test if there was a match in same time:

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

You indeed don't return when the search ID is not found. you might change to something like:

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;
}

Or return pointer:

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& 
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302