#include#include #include int main() { std::vector v = {1, 2, 3, 4, 5}; std::for_each(v.begin(), v.end(), [](int x) { std::cout << x << std::endl; }); return 0; }
#includeThis code calculates the sum of the elements in the vector v. The lambda function inside std::for_each takes an integer as a parameter and adds it to the variable sum. Both of these examples use std::for_each from the C++ Standard Library.#include #include int main() { std::vector v = {1, 2, 3, 4, 5}; int sum = 0; std::for_each(v.begin(), v.end(), [&sum](int x) { sum += x; }); std::cout << "The sum is " << sum << std::endl; return 0; }