求问以下的代码,为什么"auto& node = q.top()" 这一行,在第二次循环的时候会得到旧的 top ,而不是新的?因为这个,我的代码出现了死循环。旧的 top 不是已经被 pop 掉了么?
百思不得其解,我试了把容器换成 vector ,就正常了,或者可以把 “auto&” 的 "&" 去掉。 看了下 debugger ,如果不改代码,node 的类型是 Node * const &。 如果去掉&,类型就是 Node * ,那没问题,如果容器是 vector ,类型就是 Node * &,也是没问题的。
可是我还是没法把 Node* const &和第二轮 loop 依然得到旧的 top 值联系在一起。怎么回事?
#include <queue>
struct Node {
int val;
Node* next = nullptr;
Node(int x) : val(x){}
};
int main()
{
Node* n1 = new Node(1);
Node* n2 = new Node(2);
std::priority_queue<Node*> q;
q.push(n1);
q.push(n2);
Node* head = new Node(-1);
auto cur = head;
while (!q.empty())
{
auto& node = q.top();
q.pop();
cur->next = node;
if (node->next) q.push(node->next);
cur = cur->next;
}
}