### Lambda Expressions

In this code:

 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 // Ex10_15.cpp Using lambda expressions #include #include #include #include #include #include using namespace std; // Just to avoid a lot of using directives in the example... // Template function to return the average of the elements in a vector template T average(const vector& vec) { static_assert(std::is_arithmetic::value, "Type parameter for average() must be aithmetic."); T sum(0); for_each(vec.begin(), vec.end(), [&sum](const T& value){ sum += value; }); return sum/vec.size(); } // Template function to set a vector to values beginning with start // and incremented by increment template void setValues(vector& vec, T start, T increment) { static_assert(std::is_arithmetic::value, "Type parameter for setValues() must be aithmetic."); T current(start); generate(begin(vec), end(vec), [increment, ¤t]()->T{T result(current); current += increment; return result;}); } // Template function to set a vector to random values between min and max template void randomValues(vector& vec, T min, T max) { static_assert(std::is_arithmetic::value, "Type parameter for randomValues() must be aithmetic."); srand(static_cast(time(0))); // Initialize random // number generator generate(begin(vec), end(vec), [=](){ return static_cast(static_cast(rand())/ RAND_MAX*(max-min)+ min); }); } // Template function to list the values in a vector template void listVector(const vector& vec) { int count = 0; // Used to control outputs per line const int valuesPerLine(5); for_each(begin(vec), end(vec), [&count, valuesPerLine](const T& n)->void{ cout << setw(10) << n << " "; if(++count % valuesPerLine == 0) cout << endl;}); } int main() { vector integerData(50); randomValues(integerData, 1, 10); // Set random integer values cout << "Vector contains:" << endl; listVector(integerData); cout << "Average value is "<< average(integerData) << endl; vector realData(20); setValues(realData, 5.0, 2.5); // Set real values starting at 5.0 cout << "Vector contains:" << endl; listVector(realData); cout << "Average value is "<< average(realData) << endl; return 0; }

From my Book:

"
"line 29"

 123 [increment, ¤t]()->T{T result(current); current += increment; return result;}

The lambda accepts no arguments, but it accesses increment by value and current by reference, the latter being used to store the next value to be set. This lambda has the side effect that current will be updated when generate is finished. The following lambda expression is similar, but without the side effect:

 123 [=]()mutable->T{T result(current); current += increment; return result;}
"

I dont exactly understand what side affect it is talking about. Wouldn't you want generate to update current?

I understand how the second code fixes it though, just takes everything in the enclosing scope by value.