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.
[](){};
This doesn’t do anything, but it’s the most basic way to compile without error.
#include <iostream> int main(){ [](){}; return 0; }
Assigning Lambda Return to a Variable
auto a = [](){};
Inserting content into the body of the lambada
auto b = [](){ std::cout << "I \u2764 Lambda!\n"; };
Printing the contents of the lambda
auto c = [](){ std::cout << "I \u2764 Lambda!\n"; }; c();
Passing parameter to Lambda
auto d = []( const char * s ){ std::cout << s; }; d("I \u2764 Lambda!\n");
Returning defined type
auto e = []()->float { return 3.6f; }; std::cout << "0.9 + e = " << 0.9f + e() << '\n';
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
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';
Calling with direct parameters
int n = [] (int x, int y) { return x + y; }(5, 4); std::cout << n << '\n';
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++!