I have written simple wrapper for 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. I use heap just through proper Heap methods. When message occurs m_data are not empty.
What could be wrong with heap?
*I use 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. You should use make_heap() instead of 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>());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.