【问题标题】:accumulate with custom sum用自定义总和累积
【发布时间】:2020-10-17 17:51:49
【问题描述】:

下面的函数将字符串转换为整数,使用 std::accumulate。

它首先检查标志的存在并跳过它。 lambda 的参数c 很好,因为它只是遍历输入字符串s 的所有剩余字符。但是第一个 lambda 参数sum 呢?它怎么知道它应该将sum 初始化为零?这些 lambda 参数的顺序是否重要?

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

顺便说一句,不使用 std::accumulate 的等效代码看起来像这样:

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

【问题讨论】:

    标签: c++ stl c++14


    【解决方案1】:

    end(s) 和 lambda 之间的参数是初始值。

    可以是 1,例如,如果您想要产品。

    第一个lambda参数是累积的数据,第二个是序列的当前元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 2012-09-24
      相关资源
      最近更新 更多