Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accumulate chars in a string as digits. Lambda. C++

How can I sum all digits in a string num into an integer sum using a lambda?

string num = "1234567891011";

int sum = accumulate(num.begin(), num.end(), 0, [](auto & a, auto & b)
{
    // ???

    // return int(a - '0') + int(b - '0') causes an error
});

With this num, sum must be equal 48.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming that the num will always have chars between 0 and 9, you can accumulate as follows:

int sum = std::accumulate(num.begin(), num.end(), 0, [](int a, char b) {
        return a + (b - '0');
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading