Browse DevX
Sign up for e-mail newsletters from DevX


Statistics Made Easier with STL-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Mean and Lean
The operations required for calculating the average of a range of elements consist of summing up all the values within that range and dividing the result by the number of elements. This task can become unduly complex when you have to deal with various types of ranges and looping through containers in order to accumulate their sum. However, using the right STL algorithms, it's a cinch.

The first step consists of summing up all the values in a range. For this purpose, use the accumulate() algorithm defined in <numeric>. This algorithm accumulates all elements within a range into a single value. accumulate() has three overloaded versions, but for the sake of brevity, the first version is used here, with the following prototype:

template <typename InputIterator, typename T> T accumulate (InputIterator first, InputIterator last, T init);

The first two parameters mark the boundaries of the range. The third argument is an initial value that is added to the result. Usually, it's 0 but under certain conditions, you may need to provide a different initial value.

Author's Note: To avoid truncation and rounding problems, use the floating point datatype with the highest precision supported by your compiler—double or long double.

Suppose you have a container that stores students' grades:

vector <int> grades; grades.push_back(89); grades.push_back(74); grades.push_back(89); grades.push_back(63); grades.push_back(100);

First, accumulate all the grades:

double res=accumulate(grades.begin(), grades.end(),0);

Next, calculate the average:


You can accomplish these two operations in one shot:

double res= accumulate(grades.begin(),grades.end(),0)/double(grades.size()); cout<<"the average grade is: "<<res<<endl; //output: 83

The grades needn't be stored in a container object; you can apply accumulate() (as well as every other algorithm) and use a built-in array:

int grades[]={89, 74, 89, 63, 100}; size_t range_size=sizeof(grades)/sizeof(grades[0]); double res= accumulate(grades, grades+range_size, 0)/double(range_size);

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date