Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
Closures are inseparable from lambdas. They allow you to pass references to the lambda. For example, in a lambda you needed to change a private class variable. Without a closure, you would have to make a setter and a getter (which already changes the class interface, they can be called where it would not be worth it), pass a pointer to an object into the lambda.
And so you work with an object variable inside the lambda, as if it were a local variable of the lambda.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using IntV = vector<int>;
int main(int argc, char const *argv[]) {
IntV v = {0, 9, 4, 6, 7, 8, 5, 6};
size_t count = 0;
for_each(begin(v), end(v), [](IntV::value_type x){cout << x << " ";});
cout << endl;
sort(begin(v), end(v), [&count /*closure*/](IntV::value_type &a, IntV::value_type &b){
++count;
return a < b;
});
cout << count << endl;
for_each(begin(v), end(v), [](IntV::value_type x){cout << x << " ";});
cout << endl;
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question