C ++ Lambda表达式笔记
2026/9/3 6:16:24 网站建设 项目流程

可变规格mutable

​mutable修饰符, 默认情况下Lambda函数总是一个const函数,mutable可以取消其常量性。在使用该修饰符时,参数列表不可省略(即使参数为空)。

#include <iostream> using namespace std; int main() { int m = 0; int n = 0; [&, n] (int a) mutable { m = ++n + a; }(4); cout << m << endl << n << endl; }

Lambda表达式的返回类型会自动推导。除非你指定了返回类型,否则不必使用关键字。

#include <iostream> #include <string> #include <algorithm> #include <deque> #include<vector> using namespace std; int main(){ // remove_if应用实例 std::vector<int> vec_data = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int x = 5; vec_data.erase(std::remove_if(vec_data.begin(), vec_data.end(), [x](int n) { return n < x;}), vec_data.end()); //remove_if是删除符合条件的,保留不符合条件的 //初始 1 2 3 4 5 6 7 8 9 原始数据 //remove_if 后 5 6 7 8 9 | 6 7 8 9 竖线 | 左边是要保留的,右边是垃圾残留 //erase 删除后 5 6 7 8 9 只删竖线右边的垃圾,留下左边的 std::for_each(vec_data.begin(), vec_data.end(), [](int i) { std::cout << i << std::endl;}); }
Lambda表达式的优点
  • 可以直接在需要调用函数的位置定义短小精悍的函数,而不需要预先定义好函数
短小不需要复用函数场景
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(void) { int data[6] = { 3, 4, 12, 2, 1, 6 }; vector<int> testdata; testdata.insert(testdata.begin(), data, data + 6); // 对于比较大小的逻辑,使用lamdba不需要在重新定义一个函数 sort(testdata.begin(), testdata.end(), [](int a, int b){ return a > b; }); for(int i : testdata){ cout << i << " " ;} cout << endl; return 0; }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询