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:
| Parameter | Description |
| first | An input iterator addressing the position of the first element in the range to be operated on |
| last | An input iterator addressing the position one past the final element in the range operated on |
| f | User-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
ProblemThe 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;
}
SolutionOutput:
before: 3 4 2 9 15 267
after: 4 5 3 10 16 268
sum: 306
Example 2
ProblemThis program illustrates the use of the STL for_each() algorithm to find the cube of each value in a vector of integers. We also use the for_each() algorithm to display the values in the vector.
Workings#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> v(a, a+10);
cout << "\nHere are the initial contents of v:\n";
for_each(v.begin(), v.end(), DoDisplay);
cout << "\nAnd here are the cubes of the values in v:\n";
for_each(v.begin(), v.end(), DoCube);
for_each(v.begin(), v.end(), DoDisplay);
return 0;
}
SolutionOutput:
Here are the initial contents of v:
1 2 3 4 5 6 7 8 9 10
And here are the cubes of the values in v:
1 8 27 64 125 216 343 512 729 1000
See Also