C++ examples for STL Algorithm:accumulate
Computing the Sum and Mean of Elements in a Container with accumulate template function
#include <numeric> #include <iostream> #include <vector> using namespace std; int main() {//from ww w .jav a 2 s .c o m vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); int sum = accumulate(v.begin(), v.end(), 0); double mean = double(sum) / v.size(); cout << "sum = " << sum << endl; cout << "count = " << v.size() << endl; cout << "mean = " << mean << endl; }
A generic function to compute the mean
template<class Iter_T> double computeMean(Iter_T first, Iter_T last) { return static_cast<double>(accumulate(first, last, 0.0))/ distance(first, last); }