[英]INVALID HEAP when using STL make_heap / push_heap / pop_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;
但是有時我收到無效的HEAP標准調試消息。 我只是通過適當的堆方法使用堆。 出現消息時,m_data不為空。
堆可能有什么問題?
*我使用MSVS2010
編輯堆的數據(除了那些即將添加的數據)之后,堆被銷毀。 如果接下來使用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>());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.