Created
February 19, 2013 15:40
-
-
Save davideanastasia/4986954 to your computer and use it in GitHub Desktop.
Cumulative Average
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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