fork(1) download
  1. #include <numeric>
  2. #include <vector>
  3. #include <list>
  4. #include <array>
  5. #include <iostream>
  6. #include <iterator>
  7.  
  8. using namespace std;
  9.  
  10. template<typename C>
  11. auto avg_impl(const C & xs, input_iterator_tag) {
  12. using T = decltype(*begin(xs));
  13. auto s = accumulate(begin(xs), end(xs), make_pair(T{}, 0u),
  14. [](auto p, auto x) {
  15. return make_pair(p.first+x, p.second+1u);
  16. });
  17. return s.first/s.second;
  18. }
  19.  
  20. template<typename C>
  21. auto avg_impl(const C & xs, random_access_iterator_tag) {
  22. using T = decltype(*begin(xs));
  23. return accumulate(begin(xs), end(xs), T{}) / distance(begin(xs), end(xs));
  24. }
  25.  
  26. template<typename C>
  27. auto avg(const C & xs) {
  28. return avg_impl(xs,
  29. typename iterator_traits<decltype(begin(xs))>::iterator_category{});
  30. }
  31.  
  32. int main() {
  33. vector<int> vi{ 0, -5 };
  34. cout << "vi avg: " << avg(vi) << endl;
  35.  
  36. list<float> lf{ 0.0f, -5.5f };
  37. cout << "lf avg: " << avg(lf) << endl;
  38.  
  39. array<short, 2> as{ 0, -5 };
  40. cout << "as avg: " << avg(as) << endl;
  41.  
  42. double d[] = { 0, -5.5 };
  43. cout << "d avg: " << avg(d) << endl;
  44. }
  45.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
vi avg: -2
lf avg: -2.75
as avg: -2
d avg: -2.75