C++AlgorithmsBeginner

std::for_each()

Applies a given unary function object `p` to each element in the range `[first, last)`.

Review the syntaxStudy the examplesOpen the coding app
std::for_each(first, last, unary_op);

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Applies a given unary function object `p` to each element in the range `[first, last)`.

The `std::ach()` algorithm, found in the `<algorithm>` header, is a simple yet powerful way to apply an operation to every element within a specified range. It takes three arguments: `first` (an iterator to the beginning of the range), `last` (an iterator to one past the end of the range), and `p` (a unary function object, which can be a lambda, function pointer, or functor). This `p` is called for each element in the range. `std::ach()` has a linear time complexity, O(N), as it visits each element exactly once. It's versatile and works with any input iterator, making it suitable for various containers. While C++11 introduced range-based for loops, which are often more readable for simple iteration, `std::ach()` remains useful in scenarios where you need to pass a function object (especially a stateful functor) or when working with iterator pairs that don't directly map to a range-based for loop (e.g., sub-ranges). It returns the `p` function object, which can be useful if the functor maintains internal state that needs to be accessed after the iteration. It's a fundamental algorithm for processing collections element by element.

Quick reference

Syntax

std::for_each(first, last, unary_op);

Inputs

Parameters

firstInputIterator · An iterator to the beginning of the range.
lastInputIterator · An iterator to the end of the range (one past the last element).
unary_opUnaryFunction · A unary function object that will be applied to each element in the range.

See it in practice

Examples

1

Printing elements of a vector using a lambda

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

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

    std::cout << "Elements: ";
    std::for_each(numbers.begin(), numbers.end(), [](int n) {
        std::cout << n << " ";
    });
    std::cout << std::endl;
    return 0;
}
Output:
Elements: 10 20 30 40 50

A lambda function is passed to `std::ach()` to print each integer in the vector. The lambda takes an `int` by value.

2

Modifying elements in-place using a mutable lambda

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

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

    std::for_each(values.begin(), values.end(), [](int& n) {
        n *= 2; // Double each element
    });

    std::cout << "Doubled values: ";
    for (int n : values) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    return 0;
}
Output:
Doubled values: 2 4 6 8 10

By taking the element by reference (`int& n`), the lambda can modify the elements directly within the vector.

3

Counting elements with a stateful functor

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

struct EvenCounter {
    int count = 0;
    void operator()(int n) {
        if (n % 2 == 0) {
            count++;
        }
    }
};

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    EvenCounter counter_obj = std::for_each(nums.begin(), nums.end(), EvenCounter());

    std::cout << "Number of even elements: " << counter_obj.count << std::endl;
    return 0;
}
Output:
Number of even elements: 5

A functor (`EvenCounter`) is used to maintain a state (`count`) across iterations. `std::ach()` returns the modified functor object, allowing access to its final state.

Debug faster

Common Errors

1

Compilation Error

Cause: The `unary_op` lambda or function does not take exactly one argument, or its argument type is incompatible with the elements in the range.

Fix: Ensure the `unary_op` accepts one argument whose type matches (or is convertible from) the element type of the container (e.g., `int`, `const int&`, `int&`).

std::vector<int> v = {1,2};
std::for_each(v.begin(), v.end(), [](int a, int b){ /* ... */ }); // Lambda takes two args
2

Logical Error

Cause: Attempting to modify elements by value when a reference is needed (e.g., `[](int n){ n = 0; }` will not change the vector).

Fix: If elements need to be modified in the container, the lambda's parameter must be a non-const reference (e.g., `int& n`).

std::vector<int> v = {1, 2};
std::for_each(v.begin(), v.end(), [](int n){ n = 0; });
// v is still {1, 2}

Runtime support

Compatibility

GCC, Clang, MSVCN/AC++98+

Source: cppreference.com

Common questions

Frequently Asked Questions

Applies a given unary function object `p` to each element in the range `[first, last)`.

first: An iterator to the beginning of the range. last: An iterator to the end of the range (one past the last element). p: A unary function object that will be applied to each element in the range.

Compilation Error: Ensure the `p` accepts one argument whose type matches (or is convertible from) the element type of the container (e.g., `int`, `const int&`, `int&`). Logical Error: If elements need to be modified in the container, the lambda's parameter must be a non-const reference (e.g., `int& n`).