意義

2012-02-07 25 views
-3

假設我有意義

struct node{ 
    int val; 
    node* left; 
}; 

現在,我有一個priority_queue<node> sth; 什麼以下DO:

node temp = sth.top();// does it perform copy 
sth.pop(); 
temp.left = sth.top(); // is this allowed? 

如何從隊列中彈出一個元素,並將其存儲在temp.left

+7

您已經過了一年多的時間,並且詢問了118個問題,但仍然不知道如何在問題中對代碼示例進行格式設置? – sth 2012-02-07 17:55:27

+1

這是我第一次看到'std :: priority_queue'抱怨自己的格式。 :) – slaphappy 2012-02-07 17:59:13

+0

@sth:聽起來像懶惰。我會遠離這一個。 (lol:http://stackoverflow.com/questions/9181321/simple-c-implementation-throwing-error) – 2012-02-07 17:59:23

回答

1
node temp = sth.top();// does it perform copy 

是的,這使得在temp頂部元素,並把它存儲的副本。 temp.left指向頂層節點左指針的相同位置。請注意0​​實際上會返回一個引用,但是這一行要求提供一個副本。 node &temp = sth.top();將聲明對頂部元素的引用。

sth.pop(); 

從隊列中刪除頂層節點。 你可能剛剛在這裏破壞了你的數據結構。任何指向該節點對象的指針(例如,隊列中其他節點的左指針)現在都是無效的。

temp.left = sth.top(); // is this allowed? 

不,這不會編譯。 temp.left是一個指針,top()返回一個對象的引用。至少,您需要獲取該對象的地址:temp.left = &sth.top();