在对象的向量上使用find_if [英] Using find_if on a vector of object

查看:81
本文介绍了在对象的向量上使用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_if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆