#include <iostream> #include <vector> #include <algorithm> #include <functional> #include <numeric> #include <cmath> typedef struct Statistics { double mean; double median; double stdev; } Statistics; Statistics getMeanMedianStd( const std::vector< double > &i_vector ) { Statistics stats; std::vector < double > vector(i_vector); std::sort(vector.begin(),vector.end()); double sumD = std::accumulate(vector.begin(),vector.end(),0.0); stats.mean = sumD/double(vector.size()); std::vector < double > Diff(vector.size()); std::transform(vector.begin(),vector.end(),Diff.begin(), std::bind2nd(std::minus< double > (),stats.mean)); stats.stdev = std::inner_product(Diff.begin(),Diff.end(), Diff.begin(),0.0); stats.median = vector[std::floor(double(vector.size())/2.0)]; stats.stdev = std::sqrt(stats.stdev/vector.size()); return stats; } int main(int argc, char *argv[]) { std::vector < double > values({10.0,12.0,11.0,4.5,10,13,22,2,1}); for(unsigned int i=0; i < values.size(); ++i) { std::cout << values[i] << " " ; } std::cout << "\n"; Statistics stats = getMeanMedianStd(values); std::cout << "Mean = " << stats.mean << "\n" << "Median = " << stats.median << "\n" << "Standard Deviation = " << stats.stdev << "\n"; std::cout << " *** EXIT ***\n"; return EXIT_SUCCESS; }
PS: for the median if the array contains an even number of values, then the bigger one is chosen between the two of them.