for_each loop in C++ (original) (raw)
Last Updated : 16 Jun, 2026
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 header, it provides a simple and readable way to process elements without writing explicit loops.
- Works with arrays and STL containers such as vectors, lists, and maps.
- Supports functions, functors, and lambda expressions while improving code readability. C++ `
#include #include #include using namespace std;
void printElement(int x) { cout << x << " "; }
int main() { vector nums = {1, 2, 3, 4, 5};
for_each(nums.begin(), nums.end(), printElement);
return 0;}
`
**Explanation: The for_each() function iterates through all elements in the vector and calls printElement() for each element.
**Syntax
for_each(start_iter, end_iter, function);
**where,
- **start_iter - Iterator pointing to the first element of the range.
- **end_iter - Iterator pointing to one position past the last element.
- **function - Function, function object, or lambda expression to be applied to each element.
Working of for_each Loop
The working of for_each() is as follows:
- The algorithm receives the beginning and ending iterators of a range.
- It starts from the first element in the range.
- The specified function is applied to the current element.
- The iterator advances to the next element.
- Steps 3 and 4 repeat until the end iterator is reached.
- Control returns after all elements have been processed.
Examples of for_each()
Print Elements of an Array
The following program uses for_each() to print all elements of an array.
C++ `
#include #include using namespace std;
void print(int x) { cout << x << " "; }
int main() { int arr[] = {10, 20, 30, 40, 50};
for_each(arr, arr + 5, print);
return 0;}
`
**Explanation: The function print() is called once for every element in the array.
Using Lambda Expressions
With C++11 and later, lambda expressions can be used directly with for_each(), eliminating the need for a separate function.
C++ `
#include #include #include using namespace std;
int main() { vector nums = {1, 2, 3, 4, 5};
for_each(nums.begin(), nums.end(),
[](int x) {
cout << x * 2 << " ";
});
return 0;}
`
**Explanation: The lambda expression is executed for each element and prints its double.
Modifying Elements Using for_each()
Elements can be modified by passing them as references.
C++ `
#include #include #include using namespace std;
int main() { vector nums = {1, 2, 3, 4, 5};
for_each(nums.begin(), nums.end(),
[](int& x) {
x++;
});
for (int x : nums)
cout << x << " ";
return 0;}
`
**Explanation: Since each element is passed by reference (int&), the changes are applied directly to the vector.
Exception Handling in for_each()
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.
- If an exception occurs, iteration terminates immediately.
- Elements processed before the exception remain unaffected.
- The exception can be handled using a try-catch block.
- Invalid iterators or an invalid range passed to for_each() may result in undefined behavior.
**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.
Advantages of for_each()
The for_each() algorithm provides several benefits:
- Works with a wide variety of STL containers and arrays.
- Makes code shorter and easier to read.
- Separates iteration logic from processing logic.
- Supports functions, functors, and lambda expressions.
- Reduces the likelihood of loop-counter and iterator-related errors.