我正在尝试使用std :: find_if查找符合某些条件的对象.请考虑以下内容:
I am trying to use std::find_if to find an object that matches some criteria. Consider the following:
struct MyStruct { MyStruct(const int & id) : m_id(id) {} int m_id; }; ... std::vector<MyStruct> myVector; //... assume it contains things MyStruct toFind(1); std::vector<MyStruct>::iterator i = std::find_if(myVector.begin(), myVector.end(), ???);我不确定要在???
我看到的所有示例都有一个lambda,该lambda使用硬编码的值来检查ID.我想要的是仅在toFind的ID与向量中一项之一的ID匹配时才返回迭代器/成功.
All the examples I have seen have a lambda that uses a hard-coded value to check for the ID. What I want is to return the iterator/success only if the id of toFind matches the id of one of the items in the vector.
我看到的所有示例都没有向我展示如何传递两个参数
All the examples I have see don't show me how to pass the two parameters
编辑
其他信息 我必须使用两种不同的方案 其中有一个==运算符的结构 另一个结构中没有运算符==,并且我无法创建一个,因为针对这种情况查找匹配项的标准不像对等运算符那样严格.
Additional info There are two different scenarios I have to use this for One in which there is an == operator for the struct and another in which there is no operator == for the struct - and i can't create one because the criteria for finding a match for this scenario is not as rigid as would be used for an equivalence operator.
(感谢所有答复;我能够在一种情况下使用find(),并且在您的帮助下能够在另一种情况下使用find_if())
(And thanks to all who responded; I was able to use find() in one case and with your help was able to use find_if() for the other)
推荐答案尝试一下:
std::find_if( myVector.begin(), myVector.end(), [&toFind](const MyStruct& x) { return x.m_id == toFind.m_id;});或者,如果为MyStruct定义了适当的==重载,则可以使用find:
Alternatively, if you had defined an appropriate == overload for MyStruct, you could just use find:
std::find(myVector.begin(), myVector.end(), toFind); // requires ==当您进行某种异构查找时,通常最好使用find_if版本,例如,如果只给了您int而不是MyStruct值.
The find_if version is usually best when you have some kind of heterogeneous lookup, for example if you were just given an int, not a value of MyStruct.
更多推荐
如何将Lambda用于std :: find
发布评论