Advertisement
Gistrec

Lambda function

Jun 1st, 2018
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. // std::function< тип_результата( аргументы функции )>
  5. void test_lambda(std::function<std::string(std::string)>  i) {
  6.     std::string str = "hello world";
  7.     std::cout << i(str).c_str() << std::endl;
  8. }
  9.  
  10.  
  11. void main() {
  12.     // []                       без захвата переменных из внешней области видимости
  13.     // [=]                      все переменные захватываются по значению
  14.     // [&]                      все переменные захватываются по ссылке
  15.     // [x, y]                   захват x и y по значению
  16.     // [&x, &y]                 захват x и y по ссылке
  17.     // [in, &out]               захват in по значению, а out — по ссылке
  18.     // [=, &out1, &out2]        захват всех переменных по значению, кроме out1 и out2, 
  19.     //                          которые захватываются по ссылке
  20.     // [&, x, &y]               захват всех переменных по ссылке, кроме x…
  21.  
  22.    
  23.  
  24.     auto lambda_sum = [](int x, int y) -> int { return x + y; };
  25.     std::cout << "5 + 7 = " << lambda_sum(5, 7) << std::endl;
  26.  
  27.     // Получаем все значение по ссылке
  28.     auto lambda_increment = [](int &x) -> void { x++; };
  29.     int x = 5;
  30.     lambda_increment(x);
  31.     std::cout << "5++ = " << x << std::endl;
  32.  
  33.     // auto == std::function<std::string(std::string)>
  34.     std::function<std::string(std::string)> lambda_to_function = [](std::string &string) -> std::string { return string; };
  35.     test_lambda(lambda_to_function);
  36.  
  37.  
  38.     system("pause");
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement