10 examples of using Lambda Functions in C++

Lambdas solve a problem of readability, expressiveness and practicality.


10 examples of using Lambda Functions in C++

Lambdas solve a problem of readability, expressiveness and practicality. In this article we’ll show you 10 ways you can use it in your code.

Syntax

[](){};

Example 1

This doesn’t do anything, but it’s the most basic way to compile without error.

#include <iostream>  int main(){ [](){}; return 0; }

Example 2

Assigning Lambda Return to a Variable

auto a = [](){};


Example 3

Inserting content into the body of the lambada

auto b = [](){ std::cout << "I \u2764 Lambda!\n"; };

Example 4

Printing the contents of the lambda

auto c = [](){ std::cout << "I \u2764 Lambda!\n"; }; c();

Example 5

Passing parameter to Lambda

auto d = []( const char * s ){ std::cout << s; }; d("I \u2764 Lambda!\n");

Example 6

Returning defined type

auto e = []()->float { return 3.6f; }; std::cout << "0.9 + e = " << 0.9f + e() << '\n';


Example 7

Passing existing variables

int x, y; x = y = 0; auto f = [ x, &y ]{ ++y; std::cout << "x e y = " << x << " e " << ++y << '\n'; }; f(); // as y is reference, the value is changed // x is read-only // Output: x and y = 0 and 2

Example 8

Running inside std::remove_if and leaving the NUM(123.456.789-00) with only numbers

std::string s("123.456.789-00"); std::vector<std::string> num; for (int i = 0; i < s.length() ; i++) { num.push_back( s.substr(i, 1) ); } num.erase( std::remove_if( num.begin() , num.end(), []( std::string h )->bool{ return ( h == "-" || h == "." ); } ) , num.end() );

To see the output: for( auto z : num ){ std::cout << z; }; std::cout << '\n';


Example 9

Calling with direct parameters

int n = [] (int x, int y) { return x + y; }(5, 4); std::cout << n << '\n';

Example 10

Capturing the clause as a reference

auto indices = [&]( std::string index ){ std::cout << index << '\n'; }; indices("Starting jobs ...");

That’s all for today, small daily doses that will always keep us in tune with C++!


cpp cppdaily


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo