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
- How to delete last element from a map in C++
- How to create an unordered_map of pairs in C++?
- Full screen OpenCV / GtK application in C++ running on Raspberry PI
- C++, OpenCV and Gtk3 Windows dev environment
- How to create an unordered_map of user defined class in C++?
- Sum of Bitwise-OR of all subarrays of a given Array | Set 2
- How to delete last element from a set in C++
- attributes in C++
- Print numbers in descending order along with their frequencies
- Find sum of a number and its maximum prime factor
- How to traverse a C++ set in reverse direction
- How to Read and Print an Integer value in C++
- Difference between Definition and Declaration
- How to traverse a STL map in reverse direction?
- CSV file management using C++
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.