Skip to content

Instantly share code, notes, and snippets.

@sbliven
Created March 12, 2021 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbliven/6c2b639da560375d81c2bcc05cfe921c to your computer and use it in GitHub Desktop.
Save sbliven/6c2b639da560375d81c2bcc05cfe921c to your computer and use it in GitHub Desktop.
C++ lambda function with closure
// 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]();
}
}
@sbliven
Copy link
Author

sbliven commented Mar 12, 2021

Prints:

2
2
2

This is equivalent to python

fns = []
for i in range(3):
    def printi():
        print(i)
    fns.append(printi)
for f in fns:
    f()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment