关于priority_queue运算符重载的问题

需求是将结点指针存入优先级队列,想自定义优先级规则,但是好几种方法都报错,只有一种可以,代码如下:

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

struct compare {
    bool operator()(const ListNode* a, const ListNode* b) const
    {   return a->val > b->val;     }
};

void test3()
{
    ListNode* p1 = new ListNode(67);
    ListNode* p2 = new ListNode(29);
    ListNode* p3 = new ListNode(32);
    priority_queue<ListNode*, vector<ListNode*>, compare> pq;
    pq.push(p1);
    pq.push(p2);
    pq.push(p3);

    for(int i = 0; i < 3; ++i) {
        cout << pq.top()->val << endl;
        pq.pop();
    }
}

报错写法一:

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

struct compare {
    bool operator()(const ListNode& a, const ListNode& b) const
    {   return a.val > b.val;     }
};

void test3()
{
    ListNode* p1 = new ListNode(67);
    ListNode* p2 = new ListNode(29);
    ListNode* p3 = new ListNode(32);
    priority_queue<ListNode, vector<ListNode>, compare> pq;
    pq.push(*p1);
    pq.push(*p2);
    pq.push(*p3);

    for(int i = 0; i < 3; ++i) {
        cout << pq.top().val << endl;
        pq.pop();
    }
}

报错写法二:

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

struct compare {
    bool operator()(const ListNode a, const ListNode b) const
    {   return a.val > b.val;     }
};

void test3()
{
    ListNode* p1 = new ListNode(67);
    ListNode* p2 = new ListNode(29);
    ListNode* p3 = new ListNode(32);
    priority_queue<ListNode, vector<ListNode>, compare> pq;
    pq.push(p1);
    pq.push(p2);
    pq.push(p3);

    for(int i = 0; i < 3; ++i) {
        cout << pq.top().val << endl;
        pq.pop();
    }
}

希望熟悉这块的大佬可以指教一下

猜你喜欢

转载自www.cnblogs.com/joker1937/p/12287651.html