使用STL make_heap / push_heap / pop_heap时无效HEAP

时间:2011-11-29 21:04:38

标签: c++ stl heap

我为std :: make_heap / push_heap / pop_heap编写了简单的包装器:

template <typename T, typename Cont = std::vector<T>, typename Compare = std::less<typename Cont::value_type> >  
class Heap  
{  
public:  
    inline void init() { std::make_heap(m_data.begin(), m_data.end(), Compare()); }  
    inline void push(const T & elm) { m_data.push_back(elm); std::push_heap(m_data.begin(), m_data.end(), Compare()); }  
    inline const T & top() const { return m_data.front(); }  
    inline void pop() { std::pop_heap(m_data.begin(), m_data.end(), Compare()); m_data.pop_back(); }  

private:  
    Cont m_data;  
};  
我使用的

class DeliveryComparator
{
public:
    bool operator()(Delivery * lhs, Delivery * rhs)
    {
        if(lhs->producer != rhs->producer) return *lhs->producer < *rhs->producer;  
        if(lhs->rate == rhs->rate) return lhs->diff < rhs->diff;  
        return lhs->rate < rhs->rate; 
    }
};

Heap<Delivery*, std::vector<Delivery*>, DeliveryComparator> packages; 

但有时我会得到 INVALID HEAP 标准调试消息。 我只是通过适当的Heap方法使用堆。当消息发生时,m_data不为空。

堆有什么问题?

*我使用的是MSVS2010

1 个答案:

答案 0 :(得分:-1)

编辑堆的数据(待添加的数据除外)后,堆被销毁。如果接下来使用push_heap()方法,则会抛出此异常。您应该使用make_heap()而不是push_heap()。例如(顺便说一下,以下示例是我程序中的代码片段):

if (highHeap[0] < solvedQuestions){ 
               lowHeap[lenghOfLowHeap++] = highHeap[0]; // *It only add a new item without destroy the heap 
               highHeap[0] = solvedQuestions;
               // Update the Heap
               push_heap(lowHeap, lowHeap + lenghOfLowHeap); 
               //push_heap(highHeap, highHeap + lenghOfHighHeap, greater<int>()); // invalid heap exception. Because the heap was destroyed by "highHeap[0] = solvedQuestions;"
               make_heap(highHeap, highHeap + lenghOfHighHeap, greater<int>());
           }