2013-10-09 64 views
1

我有一個關於使用輸入和輸出迭代器的練習題。功能的標題是如下輸入和輸出迭代器

template<class InpIter,class OutpIter> 
OutpIter my_unique_copy(InpIter first, InpIter last, OutpIter result) 

該函數應的元素從所述範圍複製[第一,最後]導致。在連續的重複元素組中,只有第一個值被複制。返回值是元素複製到的範圍的末尾。 複雜性:線性

我有一個想法,做剛琢磨了一點幫助,因爲我不是迭代器舒適又不失

template<class InpIter,class OutpIter> 
OutpIter my_unique_copy(InpIter first, InpIter last, OutpIter result){ 
    InpIter current=first; 
    first++;//point to second element 
    while(first!=last){ 
     while(*first==*current){//Keep comparing elements to current to see if they're same 
      first++; 
     } 
     result=current; 
     current=first; 
     result++; 
     first++; 
    } 
    return result; 
} 
+1

好的,問題是什麼? :) – jrok

+3

編譯器不會咬人......讓自己感覺舒適的唯一方法就是試試看。 – Cogwheel

+0

您也可以使用'unique_copy()' – Kunal

回答

0

我想這是你所追求的,什麼每一步的解釋。

template<class InpIter,class OutpIter> 
OutpIter my_unique_copy(InpIter first, InpIter last, OutpIter result) 
{ 
    // keep going until end of sequence 
    while(first!=last) 
    { 
     // save current position. 
     InpIter current=first; 

     // advance first, test it against last, and if not 
     // equal, test what it references against current. 
     // repeat this until *first != *current, or first == last 
     while (++first != last && *first == *current); 

     // not matter what dropped the loop above, we still have 
     // our current, so save it off and advance result. 
     *result++ = *current; 
    } 

    // not sure why you want to return the first iterator position 
    // *past* the last insertion, but I kept this as-is regardless. 
    return result; 
} 

我希望能解釋一下。 (我不認爲我錯過了什麼,但我敢肯定,我會聽到它,如果我做到了。)

一個非常簡單的測試工具:

#include <iostream> 
#include <iterator> 
#include <algorithm> 

int main() 
{ 
    int ar[] = { 1,2,2,3,3,3,4,5,5,6,7,7,7,7,8 }; 
    int res[10] = {0}; 

    int *p = my_unique_copy(std::begin(ar), std::end(ar), res); 
    std::copy(res, p, std::ostream_iterator<int>(std::cout, " ")); 
    return 0; 
} 

輸出

1 2 3 4 5 6 7 8 
+0

真棒!我對這次迴歸不太確定,但這就是規格說明的意思。最後一件事,在while循環內我猜我們會先增加,直到它不再等於current,這意味着我們可以存儲當前並從下一個不同的值開始 –

+0

不確定我是否跟隨了最後一件事。我試圖解釋內部while循環的邏輯是如何工作的。它使用布爾短路評估來*不*先尊重'先',除非我們知道它不是'最後'。確切的順序是1.增加'第一',2。檢查它是否是'最後',如果是,中斷。 3.檢查'* first == * current',如果它們不相等,則中斷。否則回到1.希望是有道理的。 – WhozCraig

+0

如果你想知道如何在不保存'*結果'後將'current'重置爲第一次,那麼問問你自己會怎樣保存它?我們會這樣做:'current = first'。但這正是上面的代碼*內部while循環所做的。它的即將被執行(除非'first == last')。 – WhozCraig