Monday, November 6, 2017

C++17: std::transform_inclusive_scan()

C++17 added std::transform_inclusive_scan(). This is the same as std::inclusive_scan(), except a unary function is first applied to each input item. Here is an example (simulated on C++14):

#include <iostream>
#include <vector>

namespace std17
{
  template<class InputIt        , class OutputIt      ,
           class BinaryOperation, class UnaryOperation>
  OutputIt transform_inclusive_scan(InputIt         first    ,
                                    InputIt         last     ,
                                    OutputIt        d_first  ,
                                    BinaryOperation binary_op,
                                    UnaryOperation  unary_op )
  {
    *d_first = unary_op(*first);
    first++;
    d_first++;
    for (auto iter = first; iter != last; iter++)
    {
      *d_first = binary_op(unary_op(*iter), *(d_first - 1));
      d_first++;
    }
    return d_first;
  }
}
int main()
{
  std::vector<int> myInputVector{1, 2, 3, 4, 5};
  std::vector<int> myOutputVector(5);

  std17::transform_inclusive_scan(myInputVector.begin(),
                                  myInputVector.end()  ,
                                  myOutputVector.begin(),
                                  [](auto a, auto b) {return a + b;},
                                  [](auto a) {return a * a;});
  for (auto item : myOutputVector) 
  {
    std::cout << item << " ";
  }
  std::cout << std::endl;
  return 0;
}
// Output: 1 5 14 30 55
Reference: http://en.cppreference.com/w/cpp/algorithm/transform_inclusive_scan

No comments:

Post a Comment