Monday, November 13, 2017

C++17: std::for_each_n

C++17 added the std::for_each_n() algorithm that takes an iterator, a count, and a function, and applies the function to the first ‘count’ elements starting at the ‘iterator’. Here is an example:

#include <algorithm>
#include <iostream>

int main()
{
  int myArray[]{1, 2, 3, 4, 5, 6, 7};

  std::for_each_n(&myArray[0], 4, [](auto & value) {value = value * value;});

  for (auto element : myArray)
  {
    std::cout << element << " ";
  }
  std::cout << std::endl;
  return 0;
}
// Output: 1 4 9 16 5 6 7
Reference: http://en.cppreference.com/w/cpp/algorithm/for_each_n

No comments:

Post a Comment