在对象的向量上使用find

编程入门 行业动态 更新时间:2024-10-11 07:34:12
本文介绍了在对象的向量上使用find_if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个如下的向量:

class Foo { //whatever } class MyClass { int myInt; vector<Foo> foo_v; }

我们假设主要:

int main (void) { vector<MyClass> myClass_v; }

我想在myClass_v中找到一个有myInt == bar的对象。我不在乎foo_v。我想到使用find_if函数:

I want to find a object in myClass_v that has myInt==bar. I don't care about foo_v. I thought of using the find_if function:

std::find_if(myClass_v.begin(),myClass_v.end(),condition);

bool MyClass::condition(MyClass mc) { if(mc.myInt==5) return true; else return false; }

<你能告诉我我做错了什么吗?我认为find_if会调用condition(* First),First是一个指向myClass对象的指针。

However the compiler says that condition() is missing arguments. Could you tell me what am I doing wrong? I thought that find_if would call condition(*First), with First being a pointer to a myClass object.

还有另一个好方法来做同样的事情? / p>

Or is there another good way to do the same thing?

推荐答案

这不是谓词如何工作。您必须提供免费函数 bool Comparator(const MyClass& m){...} ,或构建函数对象,重载 operator()的类:

That's not how predicates work. You have to supply either a free function bool Comparator(const MyClass & m) { ... }, or build a function object, a class that overloads operator():

struct MyClassComp { explicit MyClassComp(int i) n(i) { } inline bool operator()(const MyClass & m) const { return m.myInt == n; } private: int n; }; std::find_if(v.begin(), v.end(), MyClassComp(5));

在C ++ 0x中:

std::find_if(v.begin(), v.end(), [](const MyClass & m) -> bool { return m.myInt == 5; });

这个无记录的lambda事实上等同于一个自由函数。这是一个模仿谓词对象的捕获版本:

This captureless lambda is in fact equivalent to a free function. Here is a capturing version that mimics the predicate object:

const int n = find_me(); std::find_if(v.begin(), v.end(), [n](const MyClass & m) -> bool { return m.myInt == n; });

更多推荐

在对象的向量上使用find

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

发布评论

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

>www.elefans.com

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