我有一个结构 vector 说“v”。我需要找到 ID 与给定 ID 匹配的“v”的某个项目。
我在另一篇文章中发现要走的路是“find_if”。所以我实现了以下内容:
std::find_if(v.begin(), v.end(), MatchesID(id))!= v.end();
注意:我已经按照帖子中的建议正确创建了 MatchesID 类。
现在,我如何访问包含我搜索的“id”的特定 vector 项?
我试过:
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:为了完整起见,我还基于帖子:Search for a struct item in a vector by member data
最佳答案
你说你的 vector 有struct
说类型 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));
关于c++ - 使用 find_if() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23823861/