for_each_n in C++17

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 Functor
class 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


My Personal Notes arrow_drop_up

I am undergrad from MN National Institute of Technology Allahabad Design is my passion and algorithms are my food for thought

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Practice Tags :

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.






User Actions