首页 > 解决方案 > 使用函数集 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 ')。我认为这个问题是因为将用于比较设定值的运算符,有人可以建议如何使这个工作吗?在这种情况下,如何为函数指针编写比较器?

标签: c++c++11stl

解决方案


如果您只想存储函数指针,则不需要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)对于任何指针都需要这样做


推荐阅读