我为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; 但有时我会收到无效的堆std调试消息。我只是通过正确的堆方法使用堆。当消息发生时,m_data不是空的。
堆有什么问题?
*我使用MSVS2010
发布于 2011-12-03 10:55:01
在编辑了堆的数据后(除了那些有待添加的数据),堆被销毁了。如果下一步使用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>());
}https://stackoverflow.com/questions/8317715
复制相似问题