是否可以像这样在c ++中使用set(或unordered_set)函数?
set<function<void(int)>> funcSet;
我有类似的东西
error: invalid operands to binary expression
('const std::__1::function<void (int)>' and 'const std::__1::function<void (int)>')
{return __x < __y;}
如何比较两个函数?
答案 0 :(得分:3)
set
要求使用<
对其元素进行排序。因此,要将函数放入集合中,必须首先定义函数的排序。例如,此比较考虑具有相同类型的所有函数:
#include <set>
#include <functional>
using namespace std;
typedef function<void(int)> fun;
bool operator<(const fun& f1, const fun& f2) {
return f2.target_type().name() < f2.target_type().name();
}
int main() {
set<fun> fset;
}
同样,对于unordered_set
,您必须定义std::hash<fun>
的专业化。
编辑:我从其他解决方案中借用了target
想法,以便对比进行明确定义。
Edit2:任意函数最有意义的比较可能如下所示:
struct fun_comp {
template<typename Fun1, typename Fun2>
bool operator()(const Fun1& f1, const Fun2& f2) {
const char* c1 = f1._M_functor._M_pod_data;
const char* c2 = f2._M_functor._M_pod_data;
size_t sz = sizeof(f1._M_functor._M_pod_data);
return lexicographical_compare(c1, c1+sz, c2, c2+sz);
}
};
这显然是完全不可移植的,取决于libstdc++
- 内部,并且只会使用-fno-access-control
进行编译,因此您可能不应该实际这样做。
答案 1 :(得分:1)
std::vector<std::function<void(int)>>
会有效吗?
如果您想订购您的功能,您似乎是唯一知道订单的人。
也许创建一个enum
来索引std::vector
对订购也有帮助吗?