使用 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;
但有时我会收到 INVALID HEAP std 调试消息。 我只是通过正确的堆方法来使用堆。当消息发生时m_data不为空。
堆可能出了什么问题?
*我使用MSVS2010
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑堆的数据后(待添加的除外),堆被销毁。如果接下来使用push_heap()方法,这个异常将会被抛出。您应该使用 make_heap() 而不是 push_heap()。例如(顺便说一句,以下示例是我的程序中的代码片段):
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):