Example of lambda expressions - C++ STL

C++ examples for STL:Lambda

Description

Example of lambda expressions

Demo Code

#include <iostream> 
#include <algorithm> 
using namespace std; 

int main() //from  ww  w.  j  a  v  a 2  s. c  o m
{ 
    const int size = 4; // size of array values 
    int values[ size ] = { 1, 2, 3, 4 }; // initialize values 

    // output each element multiplied by two 
    for_each( values, values + size, []( int i ) { cout << i * 2 << endl; } ); 

    int sum = 0; // initialize sum to zero 

    // add each element to sum 
    for_each( values, values + size, [ &sum ]( int i ) { sum += i; } ); 

    cout << "sum is " << sum << endl; // output sum 
}

Result


Related Tutorials