for_each_n in C++17 - GeeksforGeeks

13 Jun, 2018
The for_each_n() function was added in the C++17 technical specification. Its idea has been borrowed from the use of map in Python or Haskel. This function can be called with or without an execution policy. The execution policy lets you decide whether to utilize the new parallelization capabilities optimized to run on multiple cores or simply run it sequentially as with the previous standards. Even ignore the execution policy as all the functions have overloaded counterparts that run sequentially.
Simply put, for_each_n() helps apply a common function to all the elements of an array (or any other linear data-type). It essentially batches updates a range of elements starting from a given iterator and for a fixed number of elements from that iterator.
Syntax:
InputIt for_each_n( ExecutionPolicy&& policy,
           InputIt first, Size n, UnaryFunction f )

policy: [Optional] The execution policy to use.
The function is overloaded without its use.
first: The iterator to the first element 
you want to apply the operation on.
n: the number of elements to apply the function to.
f: the function object that is applied to the elements.  

(Note: The given code requires C++17 or later and may not run in all C++17 environments.)
// Requires C++17 or 17+// C++ program to demonstrate the use for_each_n// using function pointers as lambda expressions.#include <bits/stdc++.h>using namespace std;  /* Helper function to modify each element */int add1(int x){    return (x + 2);}  int main(){    vector<int> arr({ 1, 2, 3, 4, 5, 6 });      // The initial vector    for (auto i : arr)        cout << i << " ";    cout << endl;      // Using function pointer as third parameter    for_each_n(arr.begin(), 2, add1);      // Print the modified vector    for (auto i : arr)        cout << i << " ";    cout << endl;      // Using lambda expression as third parameter    for_each_n(arr.begin() + 2, 2, [](auto& x) { x += 2; });      // Print the modified vector    for (auto i : arr)        cout << i << " ";    cout << endl;      return 0;}
Output:
1 2 3 4 5 6
2 3 3 4 5 6
2 3 5 6 5 6

The true power and flexibility of for_each_n() can only be leveraged by the use of functors as its third argument.
(Note: The given code requires c++17 or later and may not run in all c++17 environments.)
// Requires C++17 or 17+// A C++ program to demonstrate the use for_each_n// using funcctors.#include <bits/stdc++.h>using namespace std;  // A Functorclass add_del {private:    int n;  public:    increment(int _n)        : n(_n)    {    }      // overloading () to create Functor objects    int operator()(int delta) const    {        return n + delta;    }};  int main(){    vector<int> arr({ 1, 2, 3, 4, 5, 6 });      // The initial vector    for (auto i : arr)        cout << i << " ";    cout << endl;      // Using functor as third parameter    for_each_n(arr.begin(), 2, add_del(1));    for_each_n(arr.begin() + 2, 2, add_del(2));      // Print the modified vector    for (auto i : arr)        cout << i << " ";    cout << endl;      return 0;}
Output:
1 2 3 4 5 6
2 3 5 6 5 6

cpp-algorithm-library
Loops & Control Structure
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Inline Functions in C++
Exception Handling in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Sorting a vector in C++
std::string class in C++