// // Example of using STL functions and classes. // // Program to compute, for a sequence of doubles, // their average, variance, and median. // // Average = sum of all elements / number of elements // // Variance = sum over all elements v[i] of (v[i] - average) squared. // // Median = number m such that equal numbers of v[i]'s are smaller and // larger than m -- i.e., the number "in the middle". // #include #include // has EXIT_SUCCESS #include // has sort() #include // has accumulate() #include int main(void) { cout << "Enter some numbers, ctrl-D to end:\n"; vector v; double temp; while (cin >> temp) v.push_back(temp); // Compute and print average using STL accumulate(). double average = accumulate(v.begin(), v.end(), 0.0) / v.size(); cout << "Average = " << average << endl; // Compute and print variance using loop with STL iterator. double variance = 0.0; for (vector::const_iterator pos = v.begin(); pos != v.end(); ++pos) variance += ((*pos) - average)*((*pos) - average); cout << "Variance = " << variance << endl; // Compute and print median using STL sort(). sort(v.begin(), v.end()); int lng = v.size(); if ((lng % 2) == 0) // if size is even, there are two middle elements, and median // is their average. cout << "Median = " << (v[lng/2-1] + v[lng/2])/2 << endl; else cout << "Median = " << v[lng/2] << endl; return EXIT_SUCCESS; }