如何将Lambda用于std :: find

编程入门 行业动态 更新时间:2024-10-12 01:31:54
本文介绍了如何将Lambda用于std :: find_if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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

本文发布于:2023-11-30 14:38:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650355.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   Lambda   find   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!