11.3. Computing the Sum and Mean of Elements in a Container

Problem

You want to compute the sum and mean of elements in a container of numbers.

Solution

You can use the accumulate function from the <numeric> header to compute the sum, and then divide by the size to get the mean. Example 11-5 demonstrates this using a vector.

Example 11-5. Computing the sum and mean of a container

#include <numeric>
#include <iostream>
#include <vector>

using namespace std;

int main() {
  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;
}

The program in Example 11-5 produces the following output:

sum = 10
count = 4
mean = 2.5

Discussion

The accumulate function generally provides the most efficient and simplest method to find the sum of all the elements in a container.

Even though this recipe has a relatively simple solution, writing your own generic function to compute a mean is not so easy. Example 11-6 shows one way to write such a generic function:

Example 11-6. 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);
}

The computeMean function in Example 11-6 is sufficient for most purposes but it has one restriction: it doesn’t work with input iterators ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.