简体   繁体   中英

Function that returns struct item from a vector based on structs member data

Im very new to c++ so I'm not very familiar with how lambda functions work here. I want to see if the vector 'problems' contains a struct item with a particular member value equal to 'animalProblemNumber'. I then want return the entire struct item. Below is the 'for-loop version' of what I'm trying to achieve.

I also have a function called 'checkProblem' to see if the 'Problem item' exists in the first place. Can I achieve both of these in the one function?

Thank you to who ever can help me.

Problem getProblem(int animalProblemNumber, std::vector<Problem>      problems){
for(Problem p: problems){
    if(p.treatment == animalProblemNumber){
        return p;
    }
}

}

bool checkProblem(int animalProblemNumber, std::vector<Problem> problems){    //change this to lambda 
for(Problem p: problems){
    if(p.treatment == animalProblemNumber){
        return true;
    }
}
return false;
}
  1. The return type of getProblem() will be a problem, no pun intended, if the vector does not contain at least one matching item. It will be better to return an iterator.

  2. Change the input to getProblem() a const& so that the retured iterator is valid when the function returns.

  3. After that, you can use getProblem() to implement checkProblem() .j

  4. checkProblem() can also be changed to accept a const& although it is strictly not necessary.

std::vector<Problem>::const_iterator getProblem(int animalProblemNumber,
                                                std::vector<Problem> const& problems)
{
    return std::find_if(problems.begin(), problems.end(),
                        [animalProblemNumber](Problem const& item)
                        { return item.treatment == animalProblemNumber; });
}

and

bool checkProblem(int animalProblemNumber, std::vector<Problem> const& problems)
{
   return (getProblem(animalProblemNumber, problems) != problems.end());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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