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.
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.)
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.)
1 2 3 4 5 6 2 3 5 6 5 6
- Vector of Vectors in C++ STL with Examples
- Array of Vectors in C++ STL
- Difference between Virtual function and Pure virtual function in C++
- cin get() in C++ with Examples
- Difference between Increment and Decrement Operators
- Map of Vectors in C++ STL with Examples
- Problem in comparing Floating point numbers and how to compare them correctly?
- exit(0) vs exit(1) in C/C++ with Examples
- C++ program to print all Even and Odd numbers from 1 to N
- Reverse the content of a file and store it in another
- Minimum cells to be flipped to get a 2*2 submatrix with equal elements
- Nested Loops in C++ with Examples
- _Find_first() function in C++ bitset with Examples
- _Find_next() function in C++ bitset with Examples
- Left-Right traversal of all the levels of N-ary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.