vendredi 26 juin 2020

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;
}

Aucun commentaire:

Enregistrer un commentaire