使用find_if()函数

Using the find_if() function

本文关键字:函数 if find 使用      更新时间:2023-10-16

我有一个结构体向量说"v"。我需要找到ID与给定ID匹配的"v"中的某个项目。

我在另一篇文章中发现,要走的路是"find_if"。所以我实现了如下代码:

std::find_if(v.begin(), v.end(), MatchesID(id))!= v.end();

NB:我已经正确地创建了MatchesID类,按照帖子中的建议。

现在,我如何访问包含我搜索的"id"的特定向量项?

I tried:

std::vector<int>::iterator it = std::find_if (v.begin(), v.end(), MatchesID(id));

但是它给出了错误。

编辑:错误C2440: '初始化':无法从'std::_Vector_iterator<_Ty,_Alloc>'转换为'std::_Vector_iterator<_Ty,_Alloc>'

EDIT2:为了完整起见,我也基于帖子:通过成员数据

搜索vector中的struct项

你说你的向量有struct s类型的mystruct(即,你有一个std::vector<mystruct>)。然而,您正在分配一个迭代器std::vector<mystruct>::iterator, std::find_if将返回给类型为std::vector<int>::iterator的迭代器。解决方案:

std::vector<mystruct>::iterator it = std::find_if (v.begin(), v.end(), MatchesID(id));

auto it = std::find_if (v.begin(), v.end(), MatchesID(id));

我认为这个问题应该降级为"我如何做到这一点"

auto there= std::find_if(v.begin(), v.end(), MatchesID(id))!= v.end();

答案是

#include <vector>
#include <algorithm>
struct MatchesID
{
    int id;
    MatchesID(int id): id(id){}
    bool operator()(int id){ return this-> id== id; }
};
int main()
{
    std::vector<int> v;
    std::vector<int>::iterator i= std::find_if(v.begin(), v.end(), MatchesID(42));
}

您可以将其与您的版本进行比较以查找错误