I seems to miss some point in lambda mechanism in C++. Here is the code:
std::vector<int> vec (5);
int init = 0;
std::generate(begin(vec), end(vec), [init]() mutable { return ++init; });
for (auto item : vec) {
std::cout << item << " ";
}
std::cout << std::endl << init << std::endl;
If there is no mutable
it wouldn't compile because I'm changing init
in lambda.
Now, as I understand lambda is called for each vector's item with a new fresh copy of init
which is 0.
So, 1 must be returned every time.
But the output of this piece of code is:
1 2 3 4 5
0
It looks like generate
captures by copy init
only once at the beginning of its execution. But why? Is it supposed to work like this?
for
loop and in the body of the loop you did something likevec[i] = ([init] () mutable {return ++init;})();
, because this creates one lambda function every iteration. – Eylagenerate(begin, end, lambda)
should do the same thing. – Germanize