从向量移动初始化priority_queue

Move-initialize a priority_queue from a vector?

本文关键字:queue priority 初始化 向量 移动      更新时间:2023-10-16

我看到了这个leetcode问题,并希望用优先级队列而不是向量来解决它(因此是O(nlogk)而不是O(nk))。如何使用给定的向量作为底层容器来移动初始化priority_queue?这是我尝试过的,但我显然误解了文档,因为它无法编译。

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的实例(不是类,实际上类不是C++中的一等公民,您不能将它们作为参数传递)。