Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- template <typename T>
- void printArr(const T* begin, const T* const end)
- {
- while (begin != end)
- {
- std::cout << *begin++ << ' ';
- }
- std::cout << '\n';
- }
- template <typename T, typename ReduceFunc>
- T reduce(const T* begin, const T* const end, ReduceFunc reduceFunc, T initialValue)
- {
- while (begin != end)
- {
- initialValue = reduceFunc(initialValue, *begin++);
- }
- return initialValue;
- }
- template <typename T>
- T sum(const T& prev, const T& curr)
- {
- return prev + curr;
- }
- template <typename T>
- T max(const T& prev, const T& curr)
- {
- return prev > curr ? prev : curr;
- }
- template <typename T>
- T join(const T& prev, const T& curr)
- {
- return prev * 10 + curr;
- }
- int main()
- {
- const int arrSize{ 10 };
- int arr[arrSize]{ 1,2,3,4,5,6,7,8,9,10 };
- std::cout << "sum = " << reduce(arr, arr + arrSize, sum<int>, 0) << '\n';
- std::cout << "max = " << reduce(arr, arr + arrSize, max<int>, 0) << '\n';
- std::cout << "join = " << reduce(arr, arr + 5, join<int>, 0) << '\n';
- }
Add Comment
Please, Sign In to add comment