本文介绍了在find_if中使用谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的结构。

I have a struct like this.

struct MaxWinPerElementInfo
{
   std::string paytableName;
   std::string elementName;
   long long  elementCredits;
   bool        multiplierRequired;
};

我想找到与 paytableName 。为此,我计划将 std :: find_if 与谓词函数一起使用。

I want to find the element that matches the paytableName. For that I planned to use std::find_if with a predicate function.

我在 struct MaxWinPerElementInfo as,

bool operator() ( const MaxWinPerElementInfo &elementInfo ) const
{
    return paytableName == elementInfo.paytableName;
}

现在我尝试通过调用来搜索元素,

Now I tried searching for the element by calling,

std :: find_if(elementInfo.begin(),elementInfo.end(),MaxWinPerElementInfo(paytable));

其中
elementInfo std :: vector< struct MaxWinPerElementInfo> paytable std :: string

为此,我遇到了错误,参数1的未知转换从'std :: string {aka std :: basic_string< char>}'到'const MaxWinPerElementInfo&'

For this I am getting the error, no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const MaxWinPerElementInfo&’

我不能使用c ++ 11,因为这是一个遗留代码。

I cannot use c++11 since this is a legacy code.

我在这里缺少什么?任何建议都将真正有用。

What I am missing here? Any suggestions would be really helpful.

推荐答案

std::find_if( elementInfo.begin(), elementInfo.end(),
    MaxWinPerElementInfo( paytable));

您正在尝试通过以下方式构造 MaxWinPerElementInfo 传递一个字符串。您是否有接受字符串的构造函数?我想不是,编译器会尝试调用采用const MaxWinPerElementInfo 引用的副本构造函数。如果没有定义使用单个参数的构造函数,则编译器将还原为它知道的唯一一个:复制构造函数。

You are trying to construct a MaxWinPerElementInfo by passing it a string. Do you have a constructor taking a string? I guess not so the compiler tries to call copy constructor which takes a const MaxWinPerElementInfo reference. If no constructor taking a single argument is defined, compiler will revert to the only one it knows: Copy contructor.

由于您有一个结构且成员是公共的,所以我会

Since you have a struct and members are public, I would suggest implementing this outside of the class with a functor object.

struct MaxWinPerElementInfoPayTablePredicate
{
    MaxWinPerElementInfoPayTablePredicate(const std::string& _paytableName) :
        paytableName(_paytableName) {}

    bool operator() ( const MaxWinPerElementInfo &elementInfo ) const
    {
        return paytableName == elementInfo.paytableName;
    }

    std::string paytableName;
}

然后这样称呼它:

std::find_if( elementInfo.begin(), elementInfo.end(),
    MaxWinPerElementInfoPayTablePredicate(paytable) );

这篇关于在find_if中使用谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 05:03