The lambda receives each number by value, so the vector is not changed.
It prints twice the value followed by a space.
for_each() calls it for 1, 2 and 3, giving 2 4 6.
Example 2 — Change values in place
Add 10 to every element using a reference.
C++
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
std::for_each(v.begin(), v.end(), [](int& n) { n += 10; });
std::cout << "After: ";
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Output
After: 11 12 13
How It Works
int& n is a reference, so n += 10 changes the real element in the vector.
Each of the three elements gets 10 added.
The loop afterwards prints the updated vector.
Example 3 — Build a total
Use a captured variable to add up all values.
C++
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {4, 5, 6};
int sum = 0;
std::for_each(v.begin(), v.end(), [&sum](int n) { sum += n; });
std::cout << "Sum: " << sum << '\n';
return 0;
}
Output
Sum: 15
How It Works
[&sum] lets the lambda change the outside variable sum.
The lambda adds 4, then 5, then 6.
After the call, sum holds 15.
Frequently Asked Questions
In C++, std::for_each() calls a function on every element in a range. Include <algorithm> to use it.
Include <algorithm>. It has been part of C++ since C++98, so every modern compiler supports it.
It returns the function object that was passed in, usually ignored.
They do the same job. A range-based for loop is often simpler to read. for_each() is useful when you already have a function to reuse or only want part of a range.
No. It always visits every element. Use std::find_if() or a normal loop with break when you need to stop.