Skip to content

Instantly share code, notes, and snippets.

@davideanastasia
Created February 19, 2013 15:40
Show Gist options
  • Save davideanastasia/4986954 to your computer and use it in GitHub Desktop.
Save davideanastasia/4986954 to your computer and use it in GitHub Desktop.
Cumulative Average
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <iterator>
using namespace std;
template<int begin, int end>
class Rand {
public:
Rand() {
srand( time(0) );
}
int operator()() const {
return (rand()%(end - begin) + begin);
}
};
template <typename TypeOut>
class AverageCalculator
{
public:
AverageCalculator()
: counter_()
, avg_()
{}
template <typename TypeIn>
void operator()(const TypeIn& v) {
++counter_;
avg_ = avg_ + (1.f/counter_)*(v - avg_);
}
TypeOut average() const {
return static_cast<TypeOut>(avg_);
}
private:
size_t counter_;
double avg_;
};
int main()
{
std::vector<int> v(10);
std::generate(v.begin(), v.end(), Rand<0,10>());
std::copy(v.begin(), v.end(),
std::ostream_iterator<int>(cout, " "));
std::cout << std::for_each(v.begin(), v.end(), AverageCalculator<double>()).average()
<< std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment