1

我有一个关于使用输入和输出迭代器的练习题。函数的标题如下

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

该函数应将 [first,last] 范围内的元素复制到结果。在一组连续的重复元素中,仅复制第一个值。返回值是元素复制到的范围的末尾。复杂性:线性

我知道该怎么做只是想寻求一点帮助,因为我对迭代器还不太满意

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;
}
4

1 回答 1

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 
于 2013-10-09T21:41:33.310 回答