Skip to content

Instantly share code, notes, and snippets.

@amsharifian
Created February 18, 2019 19:54
Show Gist options
  • Save amsharifian/49671f1dccd30d2fc12df6b57b34cc00 to your computer and use it in GitHub Desktop.
Save amsharifian/49671f1dccd30d2fc12df6b57b34cc00 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
namespace std17
{
template<class InputIt, class T, class BinaryOp, class UnaryOp>
T transform_reduce(InputIt first ,
InputIt last ,
T init ,
BinaryOp binop ,
UnaryOp unary_op)
{
T generalizedSum = init;
for (auto iter = first; iter != last; iter++)
{
generalizedSum = binop(unary_op(*iter), generalizedSum);
}
return generalizedSum;
}
}
int main()
{
std::vector<int> myInputVector{1, 2, 3, 4, 5};
int result;
result = std17::transform_reduce(myInputVector.begin(),
myInputVector.end() ,
0 ,
[](auto a, auto b) {return a + b;},
[](auto a ) {return a * a;});
std::cout << result << std::endl;
return 0;
}
// Output: 55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment