Monday, November 6, 2017

C++17: std::inclusive_scan()

C++17 added std::inclusive_scan(), which accepts a sequential input container and a sequential output container and iterates throught the input container while writing to the output container result of a binary operation on the previous result with the current input item. By default, the binary operation is addition, and the output container ends up with the integration of the input container. Here is an example (simulated with C++14):

#include <iostream>
#include <vector>

namespace std17
{
  template<class InputIt, class OutputIt>
  OutputIt inclusive_scan(InputIt first, InputIt last, OutputIt d_first)
  {
    *d_first = *first;
    first++;
    d_first++;
    for (auto iter = first; iter != last; iter++)
    {
      *d_first = *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::inclusive_scan(myInputVector.begin() ,
                        myInputVector.end()   ,
                        myOutputVector.begin());
  for (auto item : myOutputVector) 
  {
    std::cout << item << " ";
  }
  std::cout << std::endl;
  return 0;
}
// Output: 1 3 6 10 15
References:
http://en.cppreference.com/w/cpp/algorithm/inclusive_scan
http://www.modernescpp.com/index.php/c-17-new-algorithm-of-the-standard-template-library

No comments:

Post a Comment