#include iostream #include vector #include algorithm // lambda practice int main() { // [] 为存储需要的外部变量 可分为值获传入与地址传入 // 函数中的参数列表 // { } 函数体 auto square [](int x) {return x * x; }; auto is_even [](int x) {return x % 2 0; }; std::cout square square(10) std::endl; std::cout is_even is_even(10) std::endl;; int th 10; auto bigger [th](int x) { return x th; }; auto inc [th]() {th; }; inc(); std::cout bigger bigger(20) std::endl; std::cout inc th th std::endl; int seed 0; auto gen [seed]() mutable {return seed; }; std::cout gen seed gen() std::endl; std::cout seed seed std::endl; /* * mutable: 对类、结构体中的非静态成员变量有效。 * 作用 允许某个成员变量在const成员函数中也可以被修改 */ auto add [](auto a, auto b) { return a b; }; std::cout add float add(1.0, 6.3) std::endl; std::cout add int add(1, 7) std::endl; // - double 明确返回值类型 auto safe_div [](double a, double b) - double { return (b 0) ? 0.0 : (a / b); }; std::cout safe_div safe_div(1, 0) std::endl; std::cout safe_div safe_div(1, 2) std::endl; std::vector v {6, 2, 4, 7, 0, 55, 89, 34}; std::sort(v.begin(), v.end(), [](const auto a, const auto b) {return a b; }); for(const auto p:v) std::cout p std::endl; //transform 按照某种规则映射 std::transform(v.begin(), v.end(), v.begin(), [](int x) {return x * 2; }); for (const auto p : v) std::cout p std::endl; }