C++ / C++ Advanced Topics

Lambda Expressions in C++

This tutorial will guide you through the use of lambda expressions in C++. Lambda expressions allow you to write inline, anonymous functions that can greatly increase the readabil…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers advanced C++ concepts like namespaces, preprocessor directives, and more.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help