How to use Lambda functions in C++

I have heard of Lambda functions for a while but never had the courage to use them. Well, last week I was forced to use them. It was either waste a whole day avoiding them in my game engine or learn about them once and for all.

They are actually not that bad to learn. I want to give you a brief overview on how to use them.

So this is how a Lambda function looks like:

  std::cout<<"Hello There!";

The lambda function can be called as follows

std::cout<<"Hello There!";
}(); //Prints "Hello There"

You can also pass it to an object to get called:

auto l=[]{
    std::cout<<"Hello World!";

l(); // prints hello world

You can also specify parameters in lambdas just as you would do with any other function. The parameters are specified within parenthesis as follows:

//Lambda with parameters
auto n=[](const std::string& s){

n("Hello There");  //calling the lambda function. Prints Hello There

And of course, you can have a return value. This is done as follows:

auto z=[]()->float{
    return 4.2;

Now, inside the lambda introducer, i.e. the brackets, you can specify a capture to access data of outer scope that is not passed as an argument. The options are as follows:

  • [=] Outer scope is passed by value.
  • [&] Outer scope is passed by reference.

So for example, in the code below, x is passed by value, whereas y is passed by reference. This means that inside the lambda you can modify the value of y but not of x.

int x=3;
int y=42;

auto q=[x,&y]{
   std::cout<<"x: "<<x<<std::endl;
   std::cout<<"y: "<<y<<std::endl;

//Final result x=3 y=43

Once you get the hang of it, Lambdas are quite cool to use. You can use them in instances when you want to delete elements in a vector using a loop. For example the code below shows how you can remove all elements in a vector with values equal to 5:

//set up a vector
std::vector<int> v = { 0, 1, 5, 3, 4, 5, 6, 7, 5, 9 }; 

// removes all numbers equal to 5 from the vector
v.erase( std::remove_if(v.begin(), v.end(), [](int i)->bool{return i==5;}), v.end() );

Hope this helps :)

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.