Created
March 12, 2021 07:56
-
-
Save sbliven/6c2b639da560375d81c2bcc05cfe921c to your computer and use it in GitHub Desktop.
C++ lambda function with closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ -o closuretest -std=c++11 closuretest.cpp | |
#include <iostream> | |
#include<functional> | |
int main() { | |
int i = 0; | |
std::function<void()> fns[3]; | |
for(;i < 3; i++) { | |
fns[i] = [&i]() { | |
std::cout << i << std::endl; | |
}; | |
} | |
i--; | |
for(int j=0; j<3; j++) { | |
fns[i](); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prints:
This is equivalent to python