0

我是 C++ 的初学者。我正在尝试使用 std::priority_queue 创建一个 maxheap 和一个 minheap。只创建一个 maxheap 可以正常工作,但不能同时创建。我似乎无法理解错误。我收到以下错误:无法将 'minHeap' 从 'std::priority_queue, compare>' 转换为 '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);
    }
}
4

2 回答 2

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);
}

您必须使用参考。这是因为您需要修改原始集合。

于 2017-10-03T20:42:53.567 回答
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);
}
于 2017-10-03T20:39:08.333 回答