gpt4 book ai didi

c++ - find_if 函数构建问题

转载 作者:行者123 更新时间:2023-11-30 03:12:28 24 4
gpt4 key购买 nike

我正在尝试在 1 文件 .cpp 文件中构建以下代码块:

#include <iostream>

#include <algorithm>
using namespace std;

class test
{

public:

int a[10];
int index;

test();
~test();
bool equals(int p);
void search();
};

test::test()
{
int temp[10] = {4, 9, 5, 6, 9, 10, 9, 255, 60, 0};

memcpy(a, temp, sizeof(temp));

index = -1;
}

bool test::equals(int p)
{
return p == 9;
}

void test::search()
{
int* p = std::find_if(a, a+10, &test::equals);
while (p != a+10)
{
cout<< *p;
index = p - a;
p = std::find_if(p+1, a+10, &test::equals);
}
}

int main(int argc, char *argv[])
{
test object;

object.search();

return 0;
}

我收到如下所示的错误,我不确定在类的成员方法中使用 find_if 函数时到底发生了什么,而且每当我这样做时都会收到此错误。

1>c:\program files\microsoft visual studio 8\vc\include\algorithm(87) : error C2064: term does not evaluate to a function taking 1 arguments1>        c:\program files\microsoft visual studio 8\vc\include\algorithm(96) : see reference to function template instantiation '_InIt std::_Find_if(_InIt,_InIt,_Pr)' being compiled1>        with1>        [1>            _InIt=int *,1>            _Pr=bool (__thiscall test::* )(int)1>        ]1>        c:\testprogram\nomfc\main.cpp(32) : see reference to function template instantiation '_InIt std::find_if(_InIt,_InIt,_Pr)' being compiled1>        with1>        [1>            _InIt=int *,1>            _Pr=bool (__thiscall test::* )(int)1>        ]

最佳答案

find_if 函数需要一个可作为无参数函数调用的对象。这类似于自由函数、函数对象或静态类函数。您传入的 equals 成员函数的地址不是这些。您可以通过使 equals 函数成为自由函数或静态函数来解决此问题,因为它不需要 test 实例的任何成员。

// static
class test
{
public:
static bool equals(int p); // etc
};
int* p = std::find_if(a, a+10, &test::equals);

// free
bool equals(int p)
{
return p == 9;
}
int* p = std::find_if(a, a+10, equals);

如果您的真实代码示例要求它是一个成员函数,那么您需要传入一个函数对象,作为类实例的闭包。我赞成为此使用 Boost 绑定(bind)方法,但也有其他方法。

int* p = std::find_if(a, a+10, boost::bind(&test::equals, this, _1));

关于c++ - find_if 函数构建问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/913397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com