0
0
CppHow-ToBeginner · 3 min read

How to Use for_each in C++: Syntax and Examples

In C++, for_each is a standard library algorithm that applies a given function to every element in a range defined by two iterators. You use it by passing the start and end iterators of a container along with a function or lambda to perform an action on each element.
📐

Syntax

The for_each function requires three parameters: the beginning iterator, the ending iterator, and a function or callable object to apply to each element.

  • first: Iterator pointing to the start of the range.
  • last: Iterator pointing just past the end of the range.
  • func: A function, function pointer, or lambda that takes one element and performs an operation.
cpp
std::for_each(first, last, func);
💻

Example

This example shows how to use for_each with a vector of integers to print each number and then to increment each number by 1.

cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // Print each number
    std::for_each(numbers.begin(), numbers.end(), [](int n) {
        std::cout << n << " ";
    });
    std::cout << "\n";

    // Increment each number by 1
    std::for_each(numbers.begin(), numbers.end(), [](int &n) {
        n += 1;
    });

    // Print updated numbers
    std::for_each(numbers.begin(), numbers.end(), [](int n) {
        std::cout << n << " ";
    });
    std::cout << "\n";

    return 0;
}
Output
1 2 3 4 5 2 3 4 5 6
⚠️

Common Pitfalls

One common mistake is passing the function parameter by value when you want to modify the elements. This will not change the original container elements.

Another is forgetting that for_each works on iterators, so you must provide valid begin and end iterators.

cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> nums = {10, 20, 30};

    // Wrong: elements won't be changed because n is passed by value
    std::for_each(nums.begin(), nums.end(), [](int n) {
        n += 5; // modifies only local copy
    });

    // Correct: pass by reference to modify original elements
    std::for_each(nums.begin(), nums.end(), [](int &n) {
        n += 5;
    });

    for (int n : nums) {
        std::cout << n << " ";
    }
    std::cout << "\n";
    return 0;
}
Output
15 25 35
📊

Quick Reference

Remember these tips when using for_each:

  • Use container.begin() and container.end() as iterators.
  • Pass the function as a lambda or function pointer.
  • Use references in the lambda parameter to modify elements.
  • for_each returns the function object after processing all elements.

Key Takeaways

Use std::for_each with begin and end iterators to apply a function to each container element.
Pass elements by reference in the function to modify the original container values.
for_each works with any iterator-compatible container like vector, list, or array.
You can use lambdas for concise inline functions with for_each.
for_each returns the function object after processing, but usually you don't need to capture it.