如何修复"error: ‘_1’ was not declared in this scope"?

How to fix "error: ‘_1’ was not declared in this scope"?

本文关键字:declared not in scope was this error 何修复      更新时间:2023-10-16

我目前正在尝试将函数绑定到我打算使用的算法。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
vector<int> coll{1, 2, 3, 4, 5, 6};
vector<int>::iterator pos;
pos = find_if (coll.begin(), coll.end(), 
bind(greater<int>(),_1,3)); 
return 0;
}

并获取此错误反馈:

AlgoTesting.cpp: In function ‘int main()’:
AlgoTesting.cpp:184:41: error: ‘_1’ was not declared in this scope
bind(greater<int>(),_1,3)); // criterion
^~
AlgoTesting.cpp:184:41: note: suggested alternative:
In file included from algostuff.hpp:15:0,
from AlgoTesting.cpp:5:
/usr/include/c++/7/functional:275:34: note:   ‘std::placeholders::_1’
extern const _Placeholder<1> _1;
^~

我正在努力理解错误日志的含义。有谁知道我在这里错过了什么?

您需要包含<functional>并使用std::placeholders::_1

pos = find_if (coll.begin(), coll.end(), bind(greater<int>(),placeholders::_1,3));

更简单的选择是使用 lambda:

pos = find_if(coll.begin(), coll.end(), [](int v) { return std::greater<int>{}(v, 3); });

pos = find_if(coll.begin(), coll.end(), [](int v) { return 3 < v; });

要使用std::bind,需要包含标头#include <functional>,并且不要忘记using namespace placeholders

这篇文章还提供了一些额外的信息。