c++ - 如何修复“错误:'_1'未在此范围内声明”?
问题描述
我目前正在尝试将函数绑定到我打算使用的算法。
#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; });
推荐阅读
- grpc - 我们可以在 gRPC 中使用 inproc 传输和 pub/sub 消息传递模式吗?
- python - 查找列表中的最小数字以及它出现的次数
- php - 如何阻止用户使用一些刀片 unsing laravel 6?
- azure-devops - 通过 Powershell 向 Azure-Devops 管道作业发送多个参数
- python - 我的缩进有问题,导致程序无响应
- python - 当将文件夹作为模块导入时如何生成 Spynx 文档?
- angular-cli - 如何使用 Angular cli 生成延迟加载模块
- c# - 通过构造函数传递泛型参数
- vba - Filesystemobject Textstream,在执行 Textstream.Close 时立即消失(正在创建.vbs 扩展名)
- node.js - 如何增加expressjs中的res时间