Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

compiler errors - C++ Priority queue with custom type and comparator not working

I'm trying to use the C++ STL priority queue with a custom type and comparator, but no matter how I put it, I keep getting an error.

Does anyone know what the issue might be? I'm trying to copy the syntax from documentation but nothing has been working...

The custom type is a pointer to the ListNode class used in LeetCode:

 * 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) {}
 * };
 */

Within my class, I have a static comparison function:

static bool compare(ListNode* n1, ListNode* n2) {
    return n1->val < n2->val;
}

And I am trying to initialize the priority queue like this:

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

But I keep getting an error, saying:

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.

Thanks!

question from:https://stackoverflow.com/questions/65713719/c-priority-queue-with-custom-type-and-comparator-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should specify a function pointer type, but not a function type as the template argument for priority_queue.

Change

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

to

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...