If/when you get more familiar with the STL, you can look at the numeric header which has some neat items in it. The inner_product function in particular looks like it can be used to compute variance in a somewhat compact form:
Code:
#include <iostream>
#include <numeric>
#include <functional>
#include <cmath>
struct deviation_func
{
double mean;
deviation_func(double _mean) : mean(_mean) {}
double operator()(double lhs,double rhs)
{
return (lhs-mean) * (rhs-mean);
}
};
int main()
{
double arr[] = {2,4,4,4,5,5,7,9};
const int num_vals = sizeof(arr)/sizeof(arr[0]);
double mean = std::accumulate(arr,arr+num_vals,0.0)/num_vals;
deviation_func foo(mean);
double variance = std::inner_product(arr,arr+num_vals,arr,0.0,std::plus<double>(),foo)/num_vals;
double standard_dev = std::sqrt(variance);
std::cout << "Arithmetic mean is : " << mean << std::endl;
std::cout << "Population variance is: " << variance << std::endl;
std::cout << "Standard deviation is : " << standard_dev << std::endl;
return 0;
}
Whether it actually makes things more complicated looking or not is a matter of individual opinion. A simple loop might be best in many cases for clarity. Output of above program is below: