使用find_if()函数
Using the find_if() function
我有一个结构体向量说"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:为了完整起见,我也基于帖子:通过成员数据
你说你的向量有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));
}
您可以将其与您的版本进行比较以查找错误
相关文章:
- Insert函数不适用于2 if语句C++
- Fmod 函数清楚地输出一个预期的双精度值,但 if(fmod == 预期的双精度值)的计算结果不是 true
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- 在 if 语句中调用重载构造函数失败
- 为什么当 while 循环中的 if 条件变为 false 时,我的函数不输出最后一条语句?
- 简化 if 流函数的 while 循环中的大量 while 循环
- 在 constexpr-if 条件下比较 constexpr 函数参数会导致错误
- if-else 与三元函数调用性能
- 函数如何在不这样做的情况下在新线程上运行"as if"?
- 无法编译包含"if constexpr"的函数模板实例化
- 性能:否则如果 vs if 在已经返回的函数中
- 重构模板函数中的常量表达式 if 语句
- if, else if, else 函数未准确显示结果
- 为什么 if 语句对于运算符重载函数计算 false
- 使用 if/else if 的函数输出问题
- 'if constexpr branch'不会在模板函数内的 lambda 中被丢弃
- C++创建一个类似于 while、if 或 for 的函数
- 如何正确使用这个函数的if语句?
- 函数'If'的隐式声明
- 使用模板检查结构体中的字段,启用函数if,并在失败时给出一个漂亮的错误消息