C++ find_if function:
C++ find_if function:
我试图理解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; }
);
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- Confusion: decltype vs std::function
- 我似乎对if/else的基本语句有问题:/
- 为什么 std::function 可以作为 std::not2 的参数?
- IF function c++
- "if constexpr"与"try in constexpr function"警告的交互
- if-else 块引发"control reaches end of non-void function"警告