我正在尝试使用带有自定义类型和比较器的C++ STL优先级队列,但是不管我怎么说,我总是得到一个错误。
有人知道这个问题可能是什么吗?我试着从文档中复制语法,但什么都不起作用...
自定义类型是指向LeetCode中使用的ListNode类的指针:
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/在我的类中,我有一个静态比较函数:
static bool compare(ListNode* n1, ListNode* n2) {
return n1->val < n2->val;
}我试着像这样初始化优先级队列:
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)> pq(compare);但是我一直收到一个错误,说:
In file included from prog_joined.cpp:1:
In file included from ./precompiled/headers.h:55:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/queue:64:
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_queue.h:485:18: error: data member instantiated with function type 'bool (ListNode *, ListNode *)'
_Compare comp;
^
Line 137: Char 73: note: in instantiation of template class 'std::priority_queue<ListNode *, std::vector<ListNode *, std::allocator<ListNode *>>, bool (ListNode *, ListNode *)>' requested here
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)> pq(compare);
^
1 error generated.谢谢!
发布于 2021-01-14 13:15:19
应将函数指针类型指定为priority_queue的模板参数,而不是指定为函数类型。
变化
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)> pq(compare);至
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)*> pq(compare);
// ^发布于 2021-01-14 13:20:49
您可以定义一个lambda,而不是声明和定义静态函数。
auto compare = [](ListNode* n1, ListNode* n2) {
return n1->val < n2->val;
};因为lambda的类型是由编译器自动解析的,所以你不需要考虑像参数的类型是函数指针或函数之类的事情。
无论如何,decltype(...)都会解析为可调用的对象。
https://stackoverflow.com/questions/65713719
复制相似问题