lambda表达式使用场景及示例代码c++
lambda表达式是一种匿名函数,可以在需要函数对象的地方定义并使用,常用于STL算法、函数式编程、并行编程等场景。
示例代码:
- STL算法中使用lambda表达式
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
// 使用lambda表达式进行排序
std::sort(vec.begin(), vec.end(), [](int a, int b) { return a < b; });
// 使用lambda表达式进行遍历输出
std::for_each(vec.begin(), vec.end(), [](int n) { std::cout << n << " "; });
return 0;
}
- 函数式编程中使用lambda表达式
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
// 使用lambda表达式进行过滤
std::vector<int> result;
std::copy_if(vec.begin(), vec.end(), std::back_inserter(result), [](int n) { return n % 2 == 0; });
// 使用lambda表达式进行映射
std::transform(result.begin(), result.end(), result.begin(), [](int n) { return n * n; });
// 使用lambda表达式进行遍历输出
std::for_each(result.begin(), result.end(), [](int n) { std::cout << n << " "; });
return 0;
}
- 并行编程中使用lambda表达式
#include <iostream>
#include <vector>
#include <thread>
#include <future>
#include <numeric>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
// 使用lambda表达式进行并行计算
std::future<int> fut = std::async(std::launch::async, [&vec]() {
return std::accumulate(vec.begin(), vec.end(), 0);
});
// 其他计算任务...
// 等待并行计算结果
int sum = fut.get();
std::cout << "sum: " << sum << std::endl;
return 0;
}
``
原文地址: http://www.cveoy.top/t/topic/g1AE 著作权归作者所有。请勿转载和采集!