TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 Author Feedback Print Article Comment on this Article

# Statistics Made Easier with STL-2 : Page 2

 by Danny Kalev
 Dec 8, 2005
 Page 2 of 3

### WEBINAR:On-Demand

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:

``````
``````
First, accumulate all the grades:
``````
``````
Next, calculate the average:
``````
``````
You can accomplish these two operations in one shot:
``````
double res=

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};

double res=
``````

 Author Feedback Email Article Print Article Comment on this Article
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