c++ lambda function code example
Example 1: lambda c++
#include <iostream>
#include <string>
// returns a lambda
auto makeWalrus(const std::string& name)
{
// Capture name by reference and return the lambda.
return [&]() {
std::cout << "I am a walrus, my name is " << name << '\n'; // Undefined behavior
};
}
int main()
{
// Create a new walrus whose name is Roofus.
// sayName is the lambda returned by makeWalrus.
auto sayName{ makeWalrus("Roofus") };
// Call the lambda function that makeWalrus returned.
sayName();
return 0;
}
Example 2: cpp lambda function
#include <iostream>
using namespace std;
bool isGreater = [](int a, int b){ return a > b; }
int main() {
cout << isGreater(5, 2) << endl; // Output: 1
return 0;
}
Example 3: lambda c++
- Good website to learn lambda in c++:
https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp
https://en.cppreference.com/w/cpp/language/lambda
https://www.geeksforgeeks.org/lambda-expression-in-c/
https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
https://linuxhint.com/lambda-expressions-in-c/
Example 4: cpp lambda
struct X {
int x, y;
int operator()(int);
void f()
{
// the context of the following lambda is the member function X::f
[=]()->int
{
return operator()(this->x + y); // X::operator()(this->x + (*this).y)
// this has type X*
};
}
};