Home >Backend Development >C++ >How to replace function pointer with C++ lambda expression?

How to replace function pointer with C++ lambda expression?

PHPz
PHPzOriginal
2024-04-17 16:24:02397browse

Replacing function pointers with lambda expressions improves readability, reduces boilerplate code, and increases reusability. Specifically, lambda expressions use the following syntax: [capture list](parameter list) -> return type {body}, and can be used in practical cases such as vector sorting to improve code simplicity and maintainability.

如何用 C++ lambda 表达式替换函数指针?

Replace function pointers with C Lambda expressions

Lambda expressions were introduced in C++11, providing a simple Method to define anonymous functions or function pointers. Replacing function pointers with lambda expressions has many benefits, including:

  • Better readability
  • Reduce boilerplate code
  • Improve code reusability

Syntax

The syntax of lambda expression is as follows:

[capture list](parameter list) -> return type { body }
  • capture list: A comma within parentheses A delimited list of variables that will be captured from the scope of the lambda expression.
  • parameter list: A comma-separated parameter list within parentheses.
  • return type: The return value type of the function (optional).
  • body: The body of the function, enclosed in curly braces.

Example

The following is an example of replacing a function pointer with a lambda expression:

// 函数指针方式
int compare(int a, int b) { return a - b; }

// Lambda 表达式方式
auto compare = [](int a, int b) { return a - b; };

Practical case: sorting vectors

We can see the advantages of lambda expressions in a practical case:

#include <vector>
#include <algorithm>

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

  // 用 lambda 表达式对向量进行排序
  std::sort(v.begin(), v.end(), [](int a, int b) { return a < b; });

  // 打印排序后的向量
  for (int x : v) {
    std::cout << x << " ";
  }

  return 0;
}

In this case, lambda expressions are used to define a comparison function that is used to Sort vectors. There is no need to define separate functions, and the code is simpler and easier to understand.

The above is the detailed content of How to replace function pointer with C++ lambda expression?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn