首页 > 解决方案 > 具有自定义类型和比较器的 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.

谢谢!

标签: c++compiler-errorspriority-queue

解决方案


您应该指定函数指针类型,而不是函数类型作为priority_queue.

改变

priority_queue<ListNode*, vector<ListNode*>, decltype(compare)> pq(compare);

priority_queue<ListNode*, vector<ListNode*>, decltype(compare)*> pq(compare);
//                                                            ^

推荐阅读