Open In App

for_each_n in C++17

Improve
Improve
Like Article
Like
Save
Share
Report

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.) 

CPP




// 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 */
void add1(int& x) { x += 1; }
 
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 += 1; });
 
    // 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 4 5 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.) 

CPP




// Requires C++17 or 17+
// A C++ program to demonstrate the use for_each_n
// using functors.
#include <bits/stdc++.h>
using namespace std;
 
// A Functor
class add_del {
private:
    int n;
 
public:
    add_del(int _n)
        : n(_n)
    {
    }
 
    // overloading () to create Functor objects
    int operator()(int& delta) const { return delta += n; }
};
 
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



Last Updated : 11 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments