c++ - 具有自定义类型和比较器的 C++ 优先级队列不起作用
问题描述
我正在尝试将 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.
谢谢!
解决方案
您应该指定函数指针类型,而不是函数类型作为priority_queue
.
改变
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)> pq(compare);
至
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)*> pq(compare);
// ^
推荐阅读
- javascript - 将事件处理程序添加到在 .innerHTML 中创建的元素 ID
- c# - 使用应用服务进行通信在 uwp 平台上不起作用
- kubernetes-helm - statsd_exporter:错误:未知的短标志“-s”,在 Istio 中尝试 --help
- c++ - QtCreator 和 ClangCodeModel 插件
- google-sheets - 在非活动工作表上运行脚本
- c# - 使用事务与 Oracle.ManagedDataAccess.EntityFramework 获取插入记录的 ID 时出现问题
- java - 验证 authToken
- python - Python DataFrames:找到“几乎”相同的行
- c# - WPF 应用程序使用 System.ObjectDisposedExceptions 填充 Windows 事件日志
- routes - 如何刷新路由页面