我有一个关于使用输入和输出迭代器的练习题。该功能的标题如下
template<class InpIter,class OutpIter>
OutpIter my_unique_copy(InpIter first, InpIter last, OutpIter result)
该函数应该将范围[first,last]中的元素复制到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;
}
答案 0 :(得分: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