C++ examples for STL:Lambda
A lambda expression accessing a variable in the outer scope by reference
#include <iostream> #include <iomanip> #include <vector> // Function to modify vector elements using a lambda expression template <typename F> void modify(std::vector<double>& values, F fun) { for (auto& value : values) fun(value);//from w w w. j a v a 2 s . c o m } int main() { std::vector <double> numbers {11.5, 21.5, 41.5, 16.15, -41.5, 5.15, 6.15, 3.15, 23.15}; std::cout << "Numbers are:\n"; for (auto n : numbers) std::cout << std::setw(5) << n; std::cout << std::endl; double scale {2.0}; modify(numbers, [&scale](double& v){ v *= scale; }); std::cout << "Numbers scaled by " << scale <<" are:\n"; for (auto n : numbers) std::cout << std::setw(5) << n; std::cout << std::endl; }