错误:无法将“minHeap”从“std::priority_queue,std::greater >”转换为“std::priority_queue”

Posted

技术标签:

【中文标题】错误:无法将“minHeap”从“std::priority_queue,std::greater >”转换为“std::priority_queue”【英文标题】:error: could not convert ‘minHeap’ from ‘std::priority_queue, std::greater >’ to ‘std::priority_queue 【发布时间】:2017-10-03 20:33:35 【问题描述】:

我是 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);
    

【问题讨论】:

priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt; &gt; 不是priority_queue&lt;int&gt; priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt; &gt;priority_queue&lt;int&gt; 的类型不同... 【参考方案1】:

您正在尝试使用priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt; &gt; 类型传递变量,但您的函数需要priority_queue&lt;int&gt; 类型。

修正函数原型:

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

您必须使用引用。这是因为你需要修改原来的集合。

【讨论】:

【参考方案2】:

您的方法也必须使用正确的类型:

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

【讨论】:

以上是关于错误:无法将“minHeap”从“std::priority_queue,std::greater >”转换为“std::priority_queue”的主要内容,如果未能解决你的问题,请参考以下文章

最小堆排序MinHeap

minheap 最小堆的实现

c_cpp C ++中的MinHeap示例

Python heapq 优先队列 Maxheap

为啥有些人使用 PriorityQueue 覆盖比较器函数来实现 minheap,即使 Java 中的 PQ 默认是最小堆?

TOPk实现(python)