[英]INVALID HEAP when using STL make_heap / push_heap / pop_heap
I have written simple wrapper for std::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;
};
which I use like: 我使用像:
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;
But sometimes I get INVALID HEAP std debug message. 但是有时我收到无效的HEAP标准调试消息。 I use heap just through proper Heap methods. 我只是通过适当的堆方法使用堆。 When message occurs m_data are not empty. 出现消息时,m_data不为空。
What could be wrong with heap? 堆可能有什么问题?
*I use MSVS2010 *我使用MSVS2010
After editing the data of the heap (except those pending to add), the heap was destroyed. 编辑堆的数据(除了那些即将添加的数据)之后,堆被销毁。 If you using push_heap() method next, this exception will be thrown out. 如果接下来使用push_heap()方法,则将抛出此异常。 You should use make_heap() instead of push_heap(). 您应该使用make_heap()而不是push_heap()。 For example (btw, following example is the code snippet from my program): 例如(顺便说一句,以下示例是我程序中的代码片段):
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.