输入和输出迭代器

Input and Output Iterators

本文关键字:迭代器 输出 输入      更新时间:2023-10-16

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

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

我认为这就是你要做的,每一步都有解释。

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