C++ Lambda Expressions to calculate sum of values in vector

Description

C++ Lambda Expressions to calculate sum of values in vector

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

int main() {/*from   w w w  .  j a  v a 2s  . c  o 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"};

  string copy{original};

  reverse(copy);

  std::cout << "\"" << original << "\" reversed is \"" << copy << "\"" << std::endl;
}



PreviousNext

Related