C++ Lambda Expressions Guide

In C++, lambda expressions can be used to create anonymous functions. Lambda expressions can be used where function objects are needed, such as as function parameters, assigned to variables, or directly called.

The basic syntax of a lambda expression is as follows:

Capture list -> return type {
body of function
}

The capture list is used to capture local variables, the parameter list is used to define function parameters, the return type is used to define the function’s return value type, and the function body is used to define the function’s logic.

Here is an example using a lambda expression:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
   std::vector<int> numbers = {1, 2, 3, 4, 5};

   // 使用匿名函数作为sort函数的比较函数
   std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
      return a > b;
   });

   // 使用匿名函数打印排序后的结果
   std::for_each(numbers.begin(), numbers.end(), [](int num) {
      std::cout << num << " ";
   });

   return 0;
}

In the code above, we are using a lambda expression as the comparison function for the std::sort() function to sort numbers in descending order. We then use a lambda expression as the operation function for the std::for_each() function to print the sorted result.

bannerAds