c++ - 使用函数集 c++
问题描述
我正在尝试在 c++ 中创建一组函数指针,但在从中插入/删除元素时出错。
#include<bits/stdc++.h>
using namespace std;
void func(int x) {
cout<<x;
}
int main() {
set <function<void (int)>> mine;
mine.insert(func);
return 0;
}
我收到错误 /usr/include/c++/6/bits/stl_function.h:386:20: 错误:'operator<' 不匹配(操作数类型是 'const std::function' 和 'const std::function ')。我认为这个问题是因为将用于比较设定值的运算符,有人可以建议如何使这个工作吗?在这种情况下,如何为函数指针编写比较器?
解决方案
如果您只想存储函数指针,则不需要std::function
:
using MyFunctionPointer = void(*)(int);
void func(int x);
std::set<MyFunctionPointer> orderedSet;
int main()
{
orderedSet.emplace(func);
}
这是有效的,因为您可以比较 (for std::set
) 或散列 (for std::unordered set
) 函数指针值。但是标准库中没有实现比较或散列std::function
实例,并且没有可移植的方式在事后添加它。
编辑:正如@HolyBlackCat所指出的,虽然operator<
不需要内置函数来诱导函数指针所需的总顺序,但std::less
(由 使用std::set
)对于任何指针都需要这样做。
推荐阅读
- docker - SSH 直接进入 Docker 实例
- google-analytics - 谷歌分析。历史事件数据在哪里?
- java - 捆绑存储在变量中的数据
- azure-devops - 在 Azure DevOps 中动态设置将发布排队到审批者的人员?
- javascript - 为什么 append 不适用于输入类型文件 javaScript 更改功能?
- php - Nginx 和 php-fpm 不适用于嵌套位置
- javascript - antlr4 javascript - jsdoc 启动和正则表达式 liternal 之间的冲突
- c# - 如何在 C# 中使用 MeCab
- reactjs - DeferFn 与 PromiseFn 反应异步
- angular - 延迟加载另一个模块时路由中断