lambda 表达式是匿名函数,可用于简化代码、作为回调函数或参数化函数,优点包括简化代码、减少冗余和提高灵活性。

C++ 函数中 lambda 表达式的使用场景
lambda 表达式是一种匿名函数,可以在函数体内定义和使用。与普通函数不同,lambda 表达式没有名称,并且只能在定义它的作用域内使用。
使用场景:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 使用 lambda 表达式增加每个元素
std::for_each(numbers.begin(), numbers.end(), [](int& n) { n++; });
// 打印增加后的列表
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 5, 2, 4, 3};
// 使用 lambda 表达式对列表排序
std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a < b; });
// 打印排序后的列表
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}#include <iostream>
#include <vector>
void for_each(std::vector<int>& numbers, std::function<void(int&)> operation) {
for (int& num : numbers) {
operation(num);
}
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 使用 lambda 表达式参数化 for_each 函数
for_each(numbers, [](int& n) { n *= n; });
// 打印平方后的列表
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}优点:
以上就是C++ 函数的 lambda 표达式的使用场景是什么?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号