2013-11-01 140 views
0

我遇到了如何退出雙向鏈表中的循環,當它到達雙端結束時出現問題。如果在雙側存在一個元素,它將返回iter位置。如果沒有,它會在迭代結束時返回迭代器。我非常感謝你的幫助。謝謝在雙向鏈接列表中搜索

這裏是我的搜索功能

unique_ptr<DequeIterator<E>> find(E match) 
{ 
    assert(!is_empty()); 

     // the iter will begin from the head. 
    unique_ptr<DequeIterator<E>> iter(iter_begin()); 

     // Here is where I do not know how to get it quit when 
     // it gets to the end of the deque. 
     // ALSO it needs to check the value at the end of 
     // the deque before it quits too. 
    while(iter->value() != match) 
    { 
     iter->next(); 
    } 
    return iter; 
} 
+1

旁註:你___really___確定要使用的已分配和管理的數據的智能指針? – Zeta

+0

這不是我想要的東西,但這是我的教授要求我們做的: –

+0

@Zeta相信我,[此代碼已經通過大量的ringers](http://stackoverflow.com/questions/19719529/doubly鏈接列表以及如何將迭代器移動到下一個節點) – WhozCraig

回答

3

當然僅僅是這樣的:

while(iter != iter_end() && 
     iter->value() != match) 
{ 
    iter->next(); 
} 

return iter; 
+0

它會跳過最後一個節點,並且不會檢查它的值以查看它是否匹配? –

+0

沒關係。我很愚蠢。當最後一個節點爲nullptr時,雙端隊列處於結束狀態。感謝您的幫助 –

+0

通常在這樣的容器中,'end()'不會返回最後一個節點,而是返回它後面的「null」節點。而且,通常在一個空列表中'begin()== end()'是真的。這是爲了允許我發佈的代碼。 :-) –