2017-04-13 85 views
-1

我想在數組中找到前兩個相鄰的鄰居並將迭代器返回到第一個。在下面的代碼中,寫下「ForwardIterator next = ++ first;」並沒有給出我想要的結果,但它看起來是正確的。另一方面,寫「ForwardIterator next = first; ++ next;」工作正常。那麼,我錯過了什麼?迭代器和增量運算符

template<class ForwardIterator> 

ForwardIterator MyAdjacent(ForwardIterator first, ForwardIterator last) 
{ 
ForwardIterator next = ++first; 
while (first != last) 
{ 
    if (*first == *next) break; 
    else 
     ++first; 
     ++next; 
} 
return first; 
} 
+2

您是否意識到'next = ++ first'會突變'first'?在這段代碼中'* first == * next'應該總是成立。 –

+1

這不是你的代碼的問題,但是'++ next'在你的'else'下縮進的事實實際上並不會使它落在你的'else'之下。 – Barry

+0

您的縮進非常混亂。 ++下;應該與if/else一致。另外,我建議保持一致性,例如,在'if'之後的'break'就像'++ first'在else之後的行中一樣。 –

回答

2

ForwardIterator next = ++first;將修改first,所以next永遠是等於first。相反,嘗試:

ForwardIterator next = std::next(first); 

這會給你的遞增迭代器,而無需修改first。您需要在文件頂部的#include <iterator>。請參閱http://en.cppreference.com/w/cpp/iterator/next