我是c ++的初学者。我正在尝试使用std :: priority_queue创建maxheap和minheap。创建一个maxheap工作正常,但不是两个。我似乎无法理解错误。我收到以下错误: 无法将'minHeap'从'std :: priority_queue,比较>'转换为'std :: priority_queue' 尝试搜索互联网但无济于事。以下是代码。
void addNum(int num, priority_queue<int> maxHeap, priority_queue<int> minHeap) {
if (minHeap.size() == 0 || num > minHeap.top())
minHeap.push(num);
else if (num < minHeap.top())
maxHeap.push(num);
}
void createHeaps(vector<int> a) {
priority_queue<int> maxHeap;
priority_queue<int, vector<int>, greater<int> > minHeap;
for (int i = 0; i < a.size(); ++i) {
int num = a[i];
addNum(num, maxHeap, minHeap);
}
}
答案 0 :(得分:2)
您尝试使用priority_queue<int, vector<int>, greater<int> >
类型传递变量,但您的函数需要priority_queue<int>
类型。
纠正功能原型:
void addNum(int num, priority_queue<int>& maxHeap, priority_queue<int, vector<int>, greater<int> >& minHeap) {
if (minHeap.size() == 0 || num > minHeap.top())
minHeap.push(num);
else if (num < minHeap.top())
maxHeap.push(num);
}
您必须使用参考。这是因为您需要修改原始集合。
答案 1 :(得分:1)
您的方法也必须使用正确的类型:
void addNum(int num,
priority_queue<int, >& maxHeap,
priority_queue<int, std::vector<int>, std::greater<int>>& minHeap) {
if (minHeap.size() == 0 || num > minHeap.top())
minHeap.push(num);
else if (num < minHeap.top())
maxHeap.push(num);
}
或者你可以将你的方法模板化为更通用的
template <typename ... Ts1, typename ... Ts2>
void addNum(int num,
priority_queue<int, Ts1...>& maxHeap,
priority_queue<int, Ts2...>& minHeap) {
if (minHeap.size() == 0 || num > minHeap.top())
minHeap.push(num);
else if (num < minHeap.top())
maxHeap.push(num);
}
甚至,简单地说:
template <typename PriorityQueue1, typename PriorityQueue2>
void addNum(int num,
PriorityQueue1& maxHeap,
PriorityQueue2& minHeap) {
if (minHeap.size() == 0 || num > minHeap.top())
minHeap.push(num);
else if (num < minHeap.top())
maxHeap.push(num);
}