A case of a lambda-expression bug

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.