2016-04-24 140 views
0

你好,我有堆棧中的結構指針問題。C++,堆棧和結構指針

我有結構的堆棧:

stack<Somethink*> stack1; 

,我想推,「Somethink」

void Search(Somethink* array_Somethink, int s, int d,) { 

stack1.push(&(array_Somethink[s])); // 

while (stack1.size() != 0) { 
    int i = 0; 

    array_Somethink[i] = *(stack1.pop()); // this return a error 
    i++; 
    } 
} 

我希望有人可以給我一個提示,如何正確地推的流行陣列從這個棧中彈出

謝謝:d

+0

請發佈[MCVE],包括逐字錯誤消息。 –

+1

[將std :: stack .pop()方法的結果存儲到變量中]的可能重複(http://stackoverflow.com/questions/12206242/store-results-of-stdstack-pop-method-into-a-變量) – MicroVirus

回答

0
void Search(Somethink* array_Somethink, int s, int d,) { 

stack1.push(&(array_Somethink[s])); // 

while (!stack1.empty()) { 
    int i = 0; 

    array_Somethink[i] = *(stack1.top()); 
    stack1.pop(); 
    i++; 
    } 
} 

我修改後的代碼假定,你已經‘擁有’指針指向堆中的其他位置上的元素。如果不是這種情況,那麼你會在這裏結束內存泄漏,因爲堆棧中的指針變成了懸掛對象(泄漏)。

爲了避免內存泄漏的可能性,在這裏,如果您使用std::shared_ptr<Somethink>而不是原始指針,這可能是個好主意。然後,你的堆棧將變成std::stack< std:shared_ptr<Somethink> >

有關std :: stack操作empty(),pop(),top()的詳細信息,請參見std::stack

在那裏,你會發現解釋像這樣的:

的std ::堆棧::最高 C++庫容器的std ::堆棧 參考頂部(); const_reference top()const; 將引用返回到堆棧中的頂層元素。這是最近推送的元素。該元素將在調用pop()時被刪除。有效地調用c.back()。

+0

只有代碼。添加一些關於'pop()'簽名的解釋,以及'top()'實際做了什麼。 –

+0

你能告訴我.top()是做什麼的? 這工作,它是正確的答案! :) –

0

top將返回POIN ter,並且您正試圖將其分配給結構的一個實例。基本上你想的指針SomethinkSomethink的數組分配到一個位置

+0

AFAIR'pop()'不會返回任何東西('void'),但是'top()'/'front()'會分別返回。 –

+0

@πάνταῥεῖedited :) – perencia

+0

謝謝你,這是非常有用:) –