avr39ripe

cppReduceFPtr

Sep 22nd, 2021 (edited)
702
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. template <typename T>
  4. void printArr(const T* begin, const T* const end)
  5. {
  6.     while (begin != end)
  7.     {
  8.         std::cout << *begin++ << ' ';
  9.     }
  10.     std::cout << '\n';
  11. }
  12.  
  13. template <typename T, typename ReduceFunc>
  14. T reduce(const T* begin, const T* const end, ReduceFunc reduceFunc, T initialValue)
  15. {
  16.     while (begin != end)
  17.     {
  18.         initialValue = reduceFunc(initialValue, *begin++);
  19.     }
  20.     return initialValue;
  21. }
  22.  
  23. template <typename T>
  24. T sum(const T& prev, const T& curr)
  25. {
  26.     return prev + curr;
  27. }
  28.  
  29. template <typename T>
  30. T max(const T& prev, const T& curr)
  31. {
  32.     return prev > curr ? prev : curr;
  33. }
  34.  
  35. template <typename T>
  36. T join(const T& prev, const T& curr)
  37. {
  38.     return prev * 10 + curr;
  39. }
  40.  
  41. int main()
  42. {
  43.     const int arrSize{ 10 };
  44.     int arr[arrSize]{ 1,2,3,4,5,6,7,8,9,10 };
  45.  
  46.     std::cout << "sum = " << reduce(arr, arr + arrSize, sum<int>, 0) << '\n';
  47.     std::cout << "max = " << reduce(arr, arr + arrSize, max<int>, 0) << '\n';
  48.     std::cout << "join = " << reduce(arr, arr + 5, join<int>, 0) << '\n';
  49.  
  50. }
Add Comment
Please, Sign In to add comment