fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <algorithm>
  5.  
  6. template <typename Container, typename T = typename std::decay<decltype(*std::begin(std::declval<Container>()))>::type>
  7. T variance(Container && c)
  8. {
  9. auto b = std::begin(c), e = std::end(c);
  10. auto size = std::distance(b, e);
  11. auto sum = std::accumulate(b, e, T());
  12. auto mean = sum / size;
  13. T accum = T();
  14. for (const auto d : c)
  15. accum += (d - mean) * (d - mean);
  16. return std::sqrt(accum / (size - 1));
  17. }
  18.  
  19. int main() {
  20. // Works with vectors
  21. std::vector<double> v = { 1.0, 2.5, 3.7 };
  22. std::cout << variance(v) << std::endl;
  23.  
  24. // Works with raw arrays
  25. double a[] = { 1.0, 2.5, 3.7 };
  26. std::cout << variance(a) << std::endl;
  27.  
  28. // Ok this is ugly... But I want to enforce T=double in the function template.
  29. int b[] = { 1, 2, 4 };
  30. std::cout << variance<int (&)[3],double>(b) << std::endl;
  31.  
  32. return 0;
  33. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
1.35277
1.35277
1.52753