从向量移动初始化 priority_queue?

Move-initialize a priority_queue from a vector?

我看到了这个 leetcode question and wanted to solve it with a priority queue instead of a vector (thus O(nlogk) instead of O(nk)). How do I move-initialize the priority_queue with the given vector as the underlying container? This is what I tried but I clearly misunderstood the docs 因为它无法编译。

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

class cmp{
    public:
    bool operator()(const ListNode *a,const ListNode *b) const {
        if(b==nullptr) return false;
        return a==nullptr || a->val>b->val;
    }
};
class Solution {
    ListNode* helper(auto& lists) {
        ListNode *ans=lists.top();lists.pop();
        if(ans==nullptr) return nullptr;
        lists.push(ans->next);
        ans->next=helper(lists);
        return ans;
    }
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.empty()) return nullptr;
        priority_queue<ListNode*,vector<ListNode*>> pq(cmp,std::move(lists)); //compiler says error: 'std::move' is not a type
        return helper(pq);
    }
};

你是说

priority_queue<ListNode*, vector<ListNode*>, cmp> pq{ cmp{}, std::move(lists) };

?

您的代码失败,因为默认情况下比较器是 std::less<typename Container::value_type>(因此您必须在模板参数中明确写入 cmp)并且因为参数必须是 cmp 的实例(不是 class,实际上 classes 不是 C++ 中的 first-class 公民,你不能将它们作为参数传递)。