fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <numeric>
  4.  
  5. template<typename Iter, typename T>
  6. double mean(Iter begin, Iter end, double (T::*member))
  7. {
  8. size_t n = 0;
  9. double s = std::accumulate(begin, end, 0.0,
  10. [&](double acc, const T &t){ ++n; return acc + t.*member; }
  11. );
  12. return s / n;
  13. }
  14.  
  15. struct T
  16. {
  17. double a;
  18. double b;
  19. };
  20.  
  21. int main() {
  22. std::vector<T> v = {{1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0}};
  23. std::cout << mean(v.begin(), v.end(), &T::a) << std::endl;
  24. std::cout << mean(v.begin(), v.end(), &T::b) << std::endl;
  25. return 0;
  26. }
Success #stdin #stdout 0.01s 5528KB
stdin
Standard input is empty
stdout
3
4