![]() |
VOOZH | about |
The for_each() function in C++ is an STL algorithm that applies a specified function to every element in a given range. Defined in the <algorithm> header, it provides a simple and readable way to process elements without writing explicit loops.
1 2 3 4 5
Explanation: The for_each() function iterates through all elements in the vector and calls printElement() for each element.
for_each(start_iter, end_iter, function);
where,
The working of for_each() is as follows:
The following program uses for_each() to print all elements of an array.
10 20 30 40 50
Explanation: The function print() is called once for every element in the array.
With C++11 and later, lambda expressions can be used directly with for_each(), eliminating the need for a separate function.
2 4 6 8 10
Explanation: The lambda expression is executed for each element and prints its double.
Elements can be modified by passing them as references.
2 3 4 5 6
Explanation: Since each element is passed by reference (int&), the changes are applied directly to the vector.
The for_each() algorithm does not handle exceptions internally. If the function, functor, or lambda passed to for_each() throws an exception, the algorithm immediately stops processing the remaining elements and propagates the exception to the caller.
Note: In practice, exceptions inside for_each() are relatively uncommon. The algorithm is most often used with simple operations such as printing, modifying, or processing container elements.
The for_each() algorithm provides several benefits: