C++ find_if function:

C++ find_if function:

本文关键字:function if find C++      更新时间:2023-10-16

我试图理解find_if函数是如何工作的,我在这个参考中的例子:

http://www.cplusplus.com/reference/algorithm/find_if/

当我遵循上面参考中给出的示例时,这意味着当我使用main()时,一切都工作正常。但是,当我试图将该示例包含在类中(如下所示)时,我在编译时得到这个错误:

error: argument of type ‘bool (A::)(int)’ does not match ‘bool (A::*)(int)’

Inside my class:

 bool A::IsOdd (int i) {
  return ((i%2)==1);
}

void A::function(){
   std::vector<int> myvector;
   myvector.push_back(10);
   myvector.push_back(25);
   myvector.push_back(40);
   myvector.push_back(55);
   std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
   std::cout << "The first odd value is " << *it << 'n';
  }
谁能帮我理解为什么会发生这种情况?

A::isOdd需要是static方法。否则只能与特定的A配合使用。由于isOdd完全不依赖于成员字段,因此将其更改为static方法是节省的。更重要的是,由于它完全不依赖于类,您可以创建一个全局的isOdd:

bool isOdd(int i){
    return i % 2;
}

EDIT:根据chris的建议,您也可以使用简单的lambda (c++ 11):

auto it = std::find_if (
     myvector.begin(), 
     myvector.end(),
     [](int i) -> bool{ return i % 2; }
);