从向量移动初始化priority_queue
Move-initialize a priority_queue from a vector?
我看到了这个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++中的一等公民,您不能将它们作为参数传递)。
相关文章:
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- C++ queue.front();为什么不从第一个元素开始呢?
- 我可以擦除 std::queue 中间的节点吗?
- 获取大小时是否必须锁定 std::queue?
- 为什么我会收到"invalid conversion from 'Queue*/Stack*' to 'int'"错误消息?
- 销毁 std::queue 会导致内存错误
- 如何将一个 std::queue 的内容附加到另一个
- 使用元素加载 std::queue<uint8_t*> 的更有效方法?
- 为什么 std::queue 没有实现 insert() 而 std::d eque 实现了?
- 带有 std::vector 和 std::queue 的 Prim's 算法,我的代码有什么问题?
- C++程序在 #include 时无法编译<stack>,#include<queue>
- 是boost :: lockfree :: Queue(在多线程程序中)可锁定
- std :: queue :: pop()在其std :: unique_ptr数据上操作
- 通过 std::queue 中的元素的值获取元素的索引
- 如何索引指向数组 [queue] 的指针数组
- 像std::queue这样的c++标准库容器是否保证是可重入的
- 如何使用"priority"进行多线程处理?
- 在 boost::lockfree:queue 默认构造函数的情况下断言失败
- C++ Floating-Point van Emde Boas (vEB) Priority Queue