CallbackFunctions.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // CallbackFunctions.cpp : Diese Datei enthält die Funktion "main". Hier beginnt und endet die Ausführung des Programms.
  2. //
  3. #include <iostream>
  4. #include <vector>
  5. using namespace std;
  6. void print(vector<int> v) {
  7. for (auto x : v) cout << x << " ";
  8. cout << endl;
  9. }
  10. /*
  11. []: can only access variables which are local to it.
  12. [&]: capture all external variables by reference.
  13. [=]: capture all external variables by value.
  14. [a, &b]: capture ‘a’ by value and ‘b’ by reference.
  15. */
  16. int main() {
  17. vector<int> v1, v2;
  18. // Capture v1 and v2 by reference
  19. auto byRef = [&](int m) {
  20. v1.push_back(m);
  21. v2.push_back(m);
  22. };
  23. // Capture v1 and v2 by value
  24. auto byVal = [=](int m) mutable {
  25. v1.push_back(m);
  26. v2.push_back(m);
  27. };
  28. // Capture v1 by reference and v2 by value
  29. auto mixed = [=, &v1](int m) mutable {
  30. v1.push_back(m);
  31. v2.push_back(m);
  32. };
  33. // Push 20 in both v1 and v2
  34. byRef(20);
  35. // Push 234 in both v1 and v2
  36. byVal(234);
  37. // Push 10 in both v1 and v2
  38. mixed(10);
  39. print(v1);
  40. print(v2);
  41. return 0;
  42. }