Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::for_each: invoking a function for every element

std::for_each invokes a function for every element in [first, last); the sequential form preserves order and returns the function object.

Version: C++23

Syntax

template<class InputIterator, class Function>
constexpr Function std::for_each(
    InputIterator first, InputIterator last, Function f);

template<class ExecutionPolicy, class ForwardIterator, class Function>
void std::for_each(ExecutionPolicy&& exec,
    ForwardIterator first, ForwardIterator last, Function f);

std::for_each(first, last, f) from <algorithm> invokes f(*i) exactly once for each of the N elements, proceeding from first in range order. If the iterator is mutable, the function can modify the element. The no-policy overload is constexpr, requires a move-constructible Function, and returns f; the policy overload requires a copy-constructible Function, can reorder calls, and returns void.

The example accumulates values in an external variable, doubles every element, and prints 6 2 4 6. Any value returned by operator() is ignored. For an empty range, the function is not invoked. The external sum deliberately avoids assuming that state from arbitrary function-object copies will be combined.

Algorithms can copy function objects; when identity matters, use std::ref or external state with a sufficient lifetime. Without a policy, an exception from f propagates and earlier elements can already be changed. With a standard policy, an uncaught exception calls std::terminate, and temporary memory can fail with std::bad_alloc. Parallel mutation of shared state without synchronization is a data race; unsequenced policies additionally prohibit vectorization-unsafe operations.

Examples

#include <algorithm>
#include <array>
#include <iostream>

int main() {
    std::array values{1, 2, 3};
    int sum = 0;
    std::for_each(values.begin(), values.end(), [&](int& value) {
        sum += value;
        value *= 2;
    });
    std::cout << sum;
    for (int value : values) {
        std::cout << ' ' << value;
    }
    std::cout << '\n';
}

Result

6 2 4 6

std::for_each → 6 2 4 6

Sources