▒ 目录 ▒
🛫 问题
描述
环境
版本号 | 描述 | |
---|---|---|
文章日期 | 2023-06-09 | |
操作系统 | Win11 - 21H2 - 22000.1335 | |
C++在线工具 | https://c.runoob.com/compile/12/ | |
1️⃣ 什么是Lambda表达式
Lambda 表达式的各个部分
2️⃣ 优缺点
优点
缺点
3️⃣ 使用场景
在线C++工具
STL算法库
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
int main()
{
int x = 5;
int y = 10;
deque<int> coll = { 1, 3, 19, 5, 13, 7, 11, 2, 17 };
auto pos = find_if(coll.cbegin(), coll.cend(), [=](int i) {
return i > x && i < y;
});
cout << "find " << (pos != coll.end() ? "success" : "failed");
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
// 使用Lambda表达式对vec进行排序
std::sort(vec.begin(), vec.end(), [](int a, int b) { return a < b; });
// 输出排序后的结果
// 1 1 2 3 3 4 5 5 5 6 9
for (auto x : vec)
{
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
STL容器中需要传递比较函数(示例失败了)
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
int main()
{
auto fc = [](const std::string& a, const std::string& b) {
return a.length() < b.length();
};
std::map<std::string, int, decltype(fc)*> myMap = {{"apple", 5}, {"banana0", 10}, {"orange", 15}};
// 使用迭代器遍历map
std::cout << "使用迭代器遍历map:" << std::endl;
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
// 使用范围for循环遍历map
// std::cout << "使用范围for循环遍历map:" << std::endl;
// for (const auto& [key, value] : myMap) {
// std::cout << key << " : " << value << std::endl;
// }
return 0;
}
多线程示例
#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
int main()
{
// vector 容器存储线程
std::vector<std::thread> workers;
for (int i = 0; i < 5; i++)
{
workers.push_back(std::thread([]()
{
std::cout << "thread function\n";
}));
}
std::cout << "main thread\n";
// 通过 for_each 循环每一个线程
// 第三个参数赋值一个task任务
// 符号'[]'会告诉编译器我们正在用一个匿名函数
// lambda函数将它的参数作为线程的引用t
// 然后一个一个的join
std::for_each(workers.begin(), workers.end(), [](std::thread &t;)
{
t.join();
});
return 0;
}
4️⃣ Lambda表达式与函数指针的比较
5️⃣ 捕获列表
6️⃣ 返回值类型
Lambda表达式的返回值类型可以显式指定,也可以使用auto关键字自动推导。如果Lambda表达式的函数体只有一条语句,且该语句的返回值类型可以自动推导,则可以省略返回值类型和return关键字。
7️⃣ 工作原理
class print_class
{
public:
void operator()(void) const
{
cout << "Hello World!" << endl;
}
};
// 用构造的类创建对象,print此时就是一个函数对象
auto print = print_class();