+ 1
a loop inside a variable
how do I store a loop or function inside a variable? For example... What if I wanted to take this for loop with rand() int main () { for (int x = 0; x <= 10; x++) { cout << 2+ (rand() % 8) << endl; } } store it inside a variable and print the variable?
4 Answers
+ 8
You can store the whole thing as a string and print it. It won't loop for you though...
+ 5
the closest thing i can think of is something like this:
https://code.sololearn.com/cdGoZJCwei1z/#cpp
further reading:
http://www.cprogramming.com/tutorial/function-pointers.html
+ 4
What you want is a C++ lambda. You can create the loop inside a function (code block) and then assign that function to the lambda. Note that this requires you to use a C++11 or greater compiler.
lambda example:
auto func = [](){
for (int x = 0; x <= 10; x++) {
cout << 2+ (rand() % 8) << endl;
}
};
func(); calls the func lambda
+ 2
Thank you guys