Performs an operation for each element

View versions (1)

Definition

The for_each() algorithm is defined in the standard header <algorithm>, and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class InputIterator, class Function>
   Function for_each (
    InputIterator first, 
    InputIterator last, 
    Function f
    );

Parameters:

ParameterDescription
firstAn input iterator addressing the position of the first element in the range to be operated on
lastAn input iterator addressing the position one past the final element in the range operated on
fUser-defined function object that is applied to each element in the range

Description

The for_each() algorithm applies a specified function object to each element in a forward order within a range.

Return Value

Returns the function object.

Complexity

The complexity is linear with at most (last - first) comparisons.

References

Example 1
Problem

The following example uses a lambda function to increment all of the elements of a vector and then computes a sum of them.

Workings
#include <vector>
#include <algorithm>

struct Sum {
    Sum() { sum = 0; }
    void operator()(int n) { sum += n; }
 
    int sum;
};

int main()
{
    std::vector<int> nums{3, 4, 2, 9, 15, 267};
 
    std::cout << "before: ";
    for (auto n : nums) {
        std::cout << n << " ";
    }
    std::cout << '\n';
 
    std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });
    Sum s = std::for_each(nums.begin(), nums.end(), Sum());
 
    std::cout << "after:  ";
    for (auto n : nums) {
        std::cout << n << " ";
    }
    std::cout << '\n';
    std::cout << "sum: " << s.sum << '\n';
   
    return 0;
}
Solution

Output:

before: 3 4 2 9 15 267
after: 4 5 3 10 16 268
sum: 306

See Also