C++中的lambda表达式
时间: 2023-09-14 17:10:56 浏览: 75
在C++11中,引入了lambda表达式,它允许我们在需要函数的地方定义匿名函数,从而简化代码并增强可读性。C++中lambda表达式的语法如下:
```
[capture](parameters) -> return_type {
// 函数体
}
```
其中,`capture` 是可选的捕获列表,用于捕获变量。`parameters` 是参数列表,用于指定lambda函数接受的参数。`return_type` 是返回类型,可以省略,由编译器自动推断。`{}` 中是lambda函数的函数体。
以下是一些lambda表达式的例子:
1. 求两个数的和:
```cpp
auto add = [](int x, int y) -> int {
return x + y;
};
int result = add(2, 3); // result = 5
```
2. 捕获外部变量并进行操作:
```cpp
int multiplier = 2;
auto multiply = [multiplier](int x) -> int {
return x * multiplier;
};
int result = multiply(5); // result = 10
```
3. 使用捕获列表捕获所有外部变量:
```cpp
int a = 2, b = 3;
auto multiplyAndAdd = [&]() -> int {
return a * b + 1;
};
int result = multiplyAndAdd(); // result = 7
```
4. 在STL算法中使用lambda表达式:
```cpp
std::vector<int> numbers = {1, 2, 3, 4, 5};
int sum = 0;
std::for_each(numbers.begin(), numbers.end(), [&](int x) {
sum += x;
});
```
这些例子展示了C++中lambda表达式的基本用法,它可以用于各种场景,如函数对象、回调函数、排序和过滤等。lambda表达式使得C++代码更加简洁和灵活。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)