C++ Lambda Expressions (C++11) šŸŽÆ

beginner
24 min

C++ Lambda Expressions (C++11) šŸŽÆ

Welcome back to CodeYourCraft! Today, we're diving into the world of C++ Lambda Expressions. These are powerful tools introduced in C++11 that let you write small, anonymous functions without actually defining them. Let's explore how they can make your code cleaner and more efficient!

What are Lambda Expressions? šŸ“

Lambda Expressions are a part of C++11 that allows you to create function objects inline, without defining them separately. They're often used for writing small, one-off functions or to replace function pointers.

cpp
[ capture_clause ] ( parameters ) -> return_type { // function body }

In the above syntax,

  • capture_clause: Variables captured from the enclosing scope (optional)
  • parameters: Function arguments (optional)
  • return_type: Type of the function return value (optional)
  • function body: The code that gets executed

Creating and Using a Simple Lambda Function šŸ’”

Let's create a simple lambda function that calculates the square of a number.

cpp
#include <iostream> #include <functional> int main() { // Create a lambda function that squares its input auto square = [](int num) -> int { return num * num; }; // Use the lambda function int result = square(5); std::cout << "The square of 5 is: " << result << std::endl; return 0; }

Lambda Function Capture Clauses šŸ“

Lambda functions can capture variables from the enclosing scope if needed. This allows them to access and modify variables outside their scope.

cpp
#include <iostream> #include <functional> int main() { int counter = 0; // Create a lambda function that increments the counter auto incrementCounter = [](){ ++counter; }; // Use the lambda function several times for(int i = 0; i < 10; ++i) { incrementCounter(); } std::cout << "The counter is: " << counter << std::endl; return 0; }

Lambda Function Types šŸ“

Lambda functions can be assigned to different types based on their capture clause and return type.

cpp
using IntLambda = std::function<int(int)>; IntLambda squareLambda = [](int num) -> int { return num * num; };

Lambda Function Examples with Real-world Applications šŸ’”

Lambda functions can be used in various scenarios, such as sorting, filtering, and transforming data in STL containers.

cpp
#include <iostream> #include <vector> #include <algorithm> #include <functional> int main() { std::vector<int> numbers = {1, 4, 9, 16, 25}; // Sort the numbers in ascending order std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a < b; }); // Print the sorted numbers for(const auto& number : numbers) { std::cout << number << " "; } return 0; }

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is the purpose of Lambda Expressions in C++11?

Quick Quiz
Question 1 of 1

Which of the following is not a part of the Lambda Expression syntax?