tdao
tdao

Reputation: 17668

accumulate with custom sum

The function below convert a string to integer, making use of std::accumulate.

It first checks the presence of a sign and skips it. The parameter c of lambda is fine as it just goes through all the remaining characters of input string s. But what about the first lambda parameter sum? How does it know that it should initialise sum to zero? And does the order of these lambda parameters matter?

int string2int(const string &s)
{
    return (s[0] == '-' ? -1 : 1) *
           accumulate(begin(s) + (s[0] == '-' || s[0] == '+'), end(s), 0,
                      [](int sum, char c) {
                          return sum * 10 + c - '0';
                      });
}

Btw, equivalent code without using std::accumulate would look something like this:

int string2int(const string &s)
{
    int sign = (s[0] == '-' ? -1 : 0);
    sign = (s[0] == '+' ? 1 : sign);

    int index = 0;
    if(sign != 0)
    {
        ++index;
    }

    int result = 0;
    for (auto i = index; i < s.size(); ++i)
    {
        result = result * 10 + (s[i] - '0');
    }

    sign = (sign < 0 ? -1 : 1);
    return result * sign;
}

Upvotes: 0

Views: 192

Answers (1)

Alex Guteniev
Alex Guteniev

Reputation: 13634

The parameter between end(s) and the lambda is the initial value.

Could be 1, for example, if you wanted product.

The first lambda parameter is the accumulated data, the second is the current element of the sequence.

Upvotes: 1

Related Questions