2013-10-09 63 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