Monday, November 6, 2017

C++17: std::transform_reduce()

C++17 added std:: transform_reduce, which applies a functor, then reduces. The default functor is multiplication. Here is an example (simulated with C++14):

#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
Reference: http://en.cppreference.com/w/cpp/algorithm/transform_reduce

No comments:

Post a Comment