我有一个
priority_queue<node*, std::vector<node*>, CompareNodes> heap;
假设节点包括:
class node {
public:
int value;
int key;
int order = 1000000;
};
完成优先级队列后如何释放内存? 我的方法似乎不起作用:
while (heap.top()) {
node * t = heap.top();
heap.pop();
delete t;
}
最佳答案
看起来你会想做更像这样的事情:
while (!heap.empty())
{ /* the rest ... */ }
如果堆是空的,.top()
将抛出异常,因为没有任何东西可以返回,当你弹出元素时会发生这种情况。
此外,如果可用,您应该使用
priority_queue<std::unique_ptr<node>, std::vector<std::unique_ptr<node>>, CompareNodes> heap;
这样你就不用担心自己清理内存了。
关于c++释放priority_queue中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37169675/