ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

C ++ Lambda表达式笔记

C ++ Lambda表达式笔记 可变规格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 #includevector using namespace std; int main(){ // remove_if应用实例 std::vectorint 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 }; vectorint 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; }
返回列表