Home > Backend Development > C++ > body text

Usage and characteristics of C++ anonymous functions

PHPz
Release: 2024-04-19 09:03:02
Original
730 people have browsed it

Anonymous function, also known as lambda expression, is a function without specifying a name, used for one-time use or passing function pointer. Features include: anonymity, one-time use, closures, return type inference. In practice, it is often used for sorting or other one-time function calls.

C++ 匿名函数的用法和特点

C Usage and characteristics of anonymous functions

Anonymous functions, also called Lambda expressions, are Functions without specifying a name are usually used to define one-time-use functions or when a function pointer needs to be passed.

Syntax

The basic syntax of Lambda expression is as follows:

[capture list] (parameters) -> return type { function body }
Copy after login
  • capture list: used to capture external Variables, similar to the auto keyword in a function, can specify the variable name or reference to be captured.
  • parameters: The parameter list of the Lambda expression.
  • return type: The return type of the Lambda expression.
  • function body: The function body of the Lambda expression.

Features

  • Anonymity: Lambda expressions have no names and can only be referenced through function pointers or other syntax structures. .
  • One-time use: Lambda expressions are usually used for one-time use and will generally not be called again after being defined.
  • Closure: Lambda expressions can capture external variables to form closures, and the values ​​of external variables can be used.
  • Return type inference: The return type of a lambda expression can be inferred by the compiler unless explicitly specified.

Practical case

The following is an example of sorting vectors using Lambda expressions:

#include <vector>
#include <algorithm>

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

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

  // 输出排序后的向量
  for (auto& elem : vec) {
    std::cout << elem << " ";
  }
  std::cout << std::endl;

  return 0;
}
Copy after login

Output:

1 2 3 4 5
Copy after login

The above is the detailed content of Usage and characteristics of C++ anonymous functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!