Define Lambda Expressions to calculate sum of values in vector - C++ STL

C++ examples for STL:Lambda

Description

Define Lambda Expressions to calculate sum of values in vector

Demo Code

#include <iostream>
#include <vector>
#include <string>
using std::string;

int main() {/*from   www.ja v  a2 s . co m*/
  auto cube = [](double value) -> double { return value*value*value; };
  double x {2.5};
  std::cout << x << " cubed is " << cube(x) << std::endl;

  auto average = [](const std::vector<double>& v) -> double
                 {
                   double sum{};
                   for (const auto& x : v)
                     sum += x;
                   return sum / v.size();
                 };
  std::vector<double> data {1.5, 2.5, 3.5, 4.5, 5.5};

  std::cout << "Average of values in data is " << average(data) << std::endl;

  string original {"this is a test test this is"};

}

Result


Related Tutorials