简体   繁体   中英

Can anyone explain how custom comparator works in C++?

Ques : Given an array of linked-lists lists, each linked list is sorted in ascending order. Merge all the linked-lists into one sort linked-list and return it.

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

I don't understand how this custom comparator is working for min-heap priority_queue.

/*
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*, vector<ListNode*>, comp> pq;
        for(auto head : lists){
            if(head != NULL)
                pq.push(head);
        }
        ListNode* dummy = new ListNode(-1);
        ListNode* curr = dummy;
        while(!pq.empty()){
            curr->next = pq.top();
            pq.pop();
            curr = curr->next;
            ListNode* next = curr->next;
            if(next != NULL)
                pq.push(next);
        }
        return dummy->next;
    }
    
    struct comp{
        bool operator()(ListNode* a, ListNode* b){
            return a->val > b->val;
        }  
    };
};

Why the return val is a->val > b->val instead of a->val < b->val

std::priority_queue is documented on cppreference with:

A user-provided Compare can be supplied to change the ordering, eg using std::greater<T> would cause the smallest element to appear as the top() .

So if you want to have a priority queue where you can pop the smallest element, it expects you to pass a comparator that returns true if a > b .

(And note that you're leaking the object allocated at dummy )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM