When solving the 9-50 exercises in C + + Primer 5th, the difference between lambda expression value capture and reference capture was encountered.
To modify the captured variable sum, Add. However, there is a difference between the forgotten value capture and the reference capture. The following code uses a value capture and fails to modify the value of the sum variable:
int Main () { vector<string> v; string s; int 0 ; while (Cin >> s) V.push_back (s); For_each (V.cbegin (), V.cend (), [sum] (conststring &s) mutable {sum + = Stoi (s); }); << sum; // Output 0}
The right way:
Modifies the capture list of a lambda so that sum is expressed as &sum. The correct code after the modification is as follows:
int main () {vector <string > V; string S; int sum = 0 ; while (cin >> s) v.push_back (s); For_each (V.cbegin (), V.cend (), [ &sum] (const string &s) mutable {sum += Stoi (s);}); cout << sum; // output 1-10 cumulative and return 0 ;}
(End of full text)
A case of a lambda-expression bug