输入和输出迭代器
Input and Output Iterators
我有一个关于使用输入和输出迭代器的练习题。函数标题如下
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
相关文章:
- 集合上的输出迭代器:assign和increment迭代器
- 访问要输出的矢量迭代器元素
- 在静态库中使用输出迭代器时出现链接器错误
- 在插入容器之前转换输出迭代器
- 根据 boost::iterator_facade 定义基于代理的输出迭代器
- 如何使用迭代器显示以下代码的输出
- C++:为什么输出迭代器不支持比较操作?
- 输入迭代器可以重复读取,而输出迭代器只能写入一次
- 是C 正向/BIDI/随机迭代器总是输出迭代器
- stl风格的算法:如何管理输出迭代器
- 对大量c++错误输出完全一无所知.我认为这与预定义的函数和迭代器有关
- 如何在C++中获取任意 (STL) 输出迭代器的"assignable type"
- 无法复制到输出迭代器
- 重载输出运算符<<以使用 STL 列表迭代器
- 如何在C++中输出迭代器
- 要写入输出迭代器的模板成员函数
- 输入和输出迭代器
- std::transform 中的输入迭代器和输出迭代器来自同一个容器是否安全?
- c++ STL映射迭代器输出十六进制值
- 输入迭代器+输出迭代器+X=正向迭代器