我的问题比这个更复杂,所以我将它缩小到一个非常简单的例子,足以让我知道如何处理其余的问题。转换多个迭代器元素
说我有一个输入迭代器。我想创建一个新的输入迭代器,其中每个元素是原始输入的多个顺序元素的组合,并且具有以下模式。运行长度在输入序列中编码。
输入: { 1 1 2 3 4 4 6 7 8 9 ... }
输出: { (1) (3+4) (6+7+8+9) ... }
我想是这样的函数可以处理单个元件并递增输入开始迭代器(通过引用传递)。在我的评论中有几个问题,另外我想知道是否有一个好的方法来处理整个元素流。
编辑:我知道有一个在调用std::advance
其中tmp
迭代器递增为准确end
,这将是适用于该代码中的bug。让我们把重点放在我的其余问题上,我会解决这个问题。 编辑2:应该现在修复?
template<class TInputIterator, class TOutputIterator>
void process_single(TInputIterator& begin, TInputIterator end, TOutputIterator destination)
{
std::iterator_traits<TInputIterator>::value_type run_length = *begin;
++begin;
// is there a better way to specify run_length elements to accumulate() without having to call advance() here?
TInputIterator tmp(begin);
std::advance(tmp, run_length);
// Edited: this condition should work for the different kinds of iterators?
if ((end < tmp) || (std::distance(begin, tmp) != run_length))
throw std::range_error("The input sequence had too few elements.");
// std::plus is the default accumulate function
*destination = std::accumulate(begin, tmp, 0/*, std::plus<TInputIterator::value_type>()*/);
// should I use std::swap(begin, tmp) here instead?
begin = tmp;
}
编辑3:在应对答案,这会是更好?
template<class TInputIterator, class TOutputIterator>
TInputIterator process_single(TInputIterator begin, TInputIterator end, TOutputIterator destination)
{
typedef std::iterator_traits<TInputIterator>::value_type value_type;
value_type run_length = *begin;
++begin;
value_type sum = 0;
while (run_length > 0 && begin != end)
{
sum += *begin;
++begin;
--run_length;
}
if (run_length)
{
throw std::range_error("The input sequence had too few elements.");
}
*destination = sum;
return begin;
}
template<class TInputIterator, class TOutputIterator>
void process(TInputIterator begin, TInputIterator end, TOutputIterator destination)
{
while (begin != end)
{
begin = process_single(begin, end, destination);
}
}
我老老实实有点困惑的问题是在这里的.. – 2009-11-01 00:11:22