C++ Lambda Expression accessing a variable in the outer scope by reference

Description

C++ 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);//w  ww.  j  ava2  s.c om
}

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;
}



PreviousNext

Related