fork download
  1. #include <iostream>
  2. #include <array>
  3. #include <algorithm>
  4.  
  5. template <typename T> struct summatory
  6. {
  7. summatory() : result(T()) {}
  8. void operator()(const T& value) { result += value; std::cout << value << "; "; };
  9. T result;
  10. };
  11.  
  12. int main(int argc, char **argv)
  13. {
  14. std::array<int, 10> a {{ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 }};
  15. summatory<int> sum;
  16.  
  17. std::cout << "\nThe summation of: ";
  18. std::for_each(a.begin(), a.end(), sum);
  19. std::cout << "is: " << sum.result;
  20.  
  21. std::cout << "\nThe summation of: ";
  22. sum = std::for_each(a.begin(), a.end(), sum);
  23. std::cout << "is: " << sum.result;
  24. }
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
The summation of: 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; is: 0
The summation of: 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; is: 143