简体   繁体   English

根据结构成员数据从向量返回结构项的函数

[英]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. 我是C ++的新手,所以我对lambda函数的工作方式不太熟悉。 I want to see if the vector 'problems' contains a struct item with a particular member value equal to 'animalProblemNumber'. 我想查看向量“问题”是否包含结构项,其特定成员值等于“ animalProblemNumber”。 I then want return the entire struct item. 然后,我想返回整个struct项目。 Below is the 'for-loop version' of what I'm trying to achieve. 以下是我要实现的“ for循环版本”。

I also have a function called 'checkProblem' to see if the 'Problem item' exists in the first place. 我还具有一个名为“ checkProblem”的函数,以首先查看“问题项”是否存在。 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. 如果vector不包含至少一个匹配项,则getProblem()的返回类型将是一个问题,不是双关语。 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. 将输入更改为const& getProblem()以使返回的迭代器在函数返回时有效。

  3. After that, you can use getProblem() to implement checkProblem() .j 之后,您可以使用getProblem()实现checkProblem() j

  4. checkProblem() can also be changed to accept a const& although it is strictly not necessary. 也可以将checkProblem()更改为接受const&尽管严格没有必要。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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