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.

#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,

Working of for_each Loop

The working of for_each() is as follows:

  1. The algorithm receives the beginning and ending iterators of a range.
  2. It starts from the first element in the range.
  3. The specified function is applied to the current element.
  4. The iterator advances to the next element.
  5. Steps 3 and 4 repeat until the end iterator is reached.
  6. Control returns after all elements have been processed.

Examples of for_each()

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.

**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: