Lambda Expressions in C++

Tutorial 4 of 5

Introduction

In this tutorial, we will dive into the concept of Lambda Expressions in C++. A lambda expression is a convenient way of defining an anonymous function object right at the location where it is invoked or passed as an argument to a function.

By the end of this tutorial, you should:

  • Understand what lambda expressions are and how to use them in C++
  • Be able to write simple lambda expressions
  • Know when and why to use lambda expressions

Prerequisites

Basic knowledge of C++ syntax and functions is required. Familiarity with the STL (Standard Template Library) will be beneficial but is not necessary.

Step-by-Step Guide

A lambda expression in C++ has the following syntax:

[capture list] (parameters list) mutable(optional) exception-> return type { //code }
  • Capture list: It defines what external variables are accessible in the lambda body.
  • Parameters list: It's the same as normal functions parameters list.
  • Mutable keyword: It allows the lambda to modify the values captured by copy in the body.
  • Exception: It specifies the exception specification for the lambda.
  • Return type: It's not necessary to specify it because the compiler can infer it.
  • Lambda body: It contains the code to be executed when the lambda is called.

Code Examples

Let's look at some examples:

Example 1: Basic lambda expression

#include<iostream>
using namespace std;

int main() {
    auto lambda = []() { cout << "Hello, World!"; };
    lambda();  // Invoking the lambda expression to print "Hello, World!"
    return 0;
}

Here, auto lambda is a lambda expression that takes no arguments () and has a lambda body that prints "Hello, World!". The lambda expression is invoked with lambda().

Expected output:

Hello, World!

Example 2: Lambda with parameters

#include<iostream>
using namespace std;

int main() {
    auto lambda = [](int x, int y) { return x + y; };
    cout << lambda(5, 7);  // Invoking the lambda expression to add 5 and 7
    return 0;
}

This lambda expression takes two integers as arguments and returns their sum.

Expected output:

12

Summary

Lambda expressions are a powerful feature in C++, allowing you to write inline, anonymous functions. They can improve the readability and maintainability of your code, especially when used with STL algorithms.

The next step to further understand lambda expressions is to practice with more complex examples and different types of capture lists.

Practice Exercises

Exercise 1: Write a lambda expression that takes an integer and multiplies it by 2.

Solution:

auto lambda = [](int x) { return x * 2; };
cout << lambda(5);  // Should print 10

Exercise 2: Write a lambda expression that captures a local variable by value and multiplies it with an argument.

Solution:

int multiplier = 5;
auto lambda = [multiplier](int x) { return x * multiplier; };
cout << lambda(2);  // Should print 10

Exercise 3: Write a lambda expression that captures all local variables by reference and modify them inside the lambda body.

Solution:

int value = 5;
auto lambda = [&value]() mutable { value *= 2; };
lambda();
cout << value;  // Should print 10

Happy Coding!