这个答案可能比你想的要复杂一些,但至少它不像我担心的那样离谱。这个想法是首先创建一个迭代器类型,该类型充当从“普通”算法到 Boost 累加器风格算法的适配器。这是比我真正预期的要简单的部分:
#ifndef ACCUM_ITERATOR_H_INCLUDED
#define ACCUM_ITERATOR_H_INCLUDED
#include <iterator>
template <class Accumulator>
class accum_iterator :
public std::iterator<std::output_iterator_tag,void,void,void,void> {
protected:
Accumulator &accumulator;
public:
typedef Accumulator accumulator_type;
explicit accum_iterator(Accumulator& x) : accumulator(x) {}
// The only part that really does anything: handle assignment by
// calling the accumulator with the value.
accum_iterator<Accumulator>&
operator=(typename Accumulator::sample_type value) {
accumulator(value);
return *this;
}
accum_iterator<Accumulator>& operator*() { return *this; }
accum_iterator<Accumulator>& operator++() { return *this; }
accum_iterator<Accumulator> operator++(int) { return *this; }
};
// A convenience function to create an accum_iterator for a given accumulator.
template <class Accumulator>
accum_iterator<Accumulator> to_accum(Accumulator &accum) {
return accum_iterator<Accumulator>(accum);
}
#endif
然后是有点不幸的部分。标准库有一个adjacent_difference 算法,它应该产生你想要的流(集合中相邻项目之间的差异)。但是它有一个严重问题:有人认为它会产生一个与输入集合大小相同的结果集合(即使显然比结果多一个输入)。为此,adjacent_difference 将结果中的第一项保留为一些未指定的值,因此您必须忽略第一个值才能从中获得任何有用的信息。
为了弥补这一点,我重新实现了一种算法类似 std::adjacent_difference 有一个非常小的区别:因为显然结果比输入少一个,所以它只有 产生的结果比输入少一个,并且不会在结果中给出无意义的、未指定的值。将两者结合,我们得到:
#include "accum_iterator.h"
#include <iostream>
#include <vector>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/mean.hpp>
using namespace boost::accumulators;
// A re-implementation of std::adjacent_difference, but with sensible outputs.
template <class InIt, class OutIt>
void diffs(InIt in1, InIt in2, OutIt out) {
typename InIt::value_type prev = *in1;
++in1;
while (in1 != in2) {
typename InIt::value_type temp = *in1;
*out++ = temp - prev;
prev = temp;
++in1;
}
}
int main() {
// Create the accumulator.
accumulator_set<double, features< tag::mean > > acc;
// Set up the test values.
std::vector<double> values;
values.push_back(13);
values.push_back(16);
values.push_back(17);
values.push_back(20);
// Use diffs to compute the differences, and feed the results to the
// accumulator via the accum_iterator:
diffs(values.begin(), values.end(), to_accum(acc));
// And print the result from the accumulator:
std::cout << "Mean: " << mean(acc) << std::endl;
return 0;
}