【问题标题】:using accumulate in C++ with a const function as parameter在 C++ 中使用以 const 函数作为参数的累积
【发布时间】:2021-03-27 11:21:50
【问题描述】:

我找不到任何解决方案,所以我发布了一个新主题。 我必须使用带有 const 函数的累积作为参数(为测试做一些练习):

  1. get_skills() - 返回技能列表,定义为:

    const vector<string>& get_skills() const;
    
  2. 我必须返回所有技能长度的总和

我尝试过的:

double sum1 = accumulate(tmpObj.get_skills().begin(), tmpObj.get_skills().end(), 0., [](const string& s, const double& sum){return s.size() + sum;});

和我一起:

 no matching function for call to object of type lambda
 note: candidate function not viable: no known conversion from 'double' to 'const std::__cxx11::string' (aka 'const basic_string<char>') for 1st argument

有人可以解释一下使用什么作为 lambda(我尝试使用 tmpObj& 但没有改变任何东西) 以及是什么导致“从 'double' 到 'const std::__cxx11::string' 的未知转换”

提前谢谢你!

【问题讨论】:

  • accumulate,尤其是BinaryOperation op的先决条件。
  • reference documentation中的例子还不够清楚吗?你在那里特别缺少什么?您似乎误解了应该如何使用std::accumulate(),您不能将stringdoubles 添加。
  • @πάνταῥεῖ 我无法使用参考文档解决它。我不明白的是,我应该在 [] 中添加什么。而且我在使用 s.size() 时打错了字。我试图将 s.length() 添加到总和中,所以我并没有真正将字符串添加到双精度

标签: c++ stl accumulate


【解决方案1】:

如果不玩视图,您可以先转换为字符串长度,然后再累加。视图会更好,但这很简单。

#include <string>
#include <iostream>
#include <numeric>
#include <vector>
#include <algorithm>


int main(int, char**)
{
    std::vector<std::string> skills = { "a", "ab", "abc" };
    std::vector<std::size_t> lengths;

    // transform to string lengths first
    std::transform(
            skills.begin(),
            skills.end(),
            std::back_inserter(lengths),
            [](const std::string& s){ return s.size(); }
    );

    // then accululate
    std::size_t sum = std::accumulate(lengths.begin(), lengths.end(), 0);
    std::cout << "sum = " << sum << '\n';

    return 0;
}

附言我应该补充一点,如果这样做,您也可以手动进行,但我想根据问题举一个例子。

【讨论】:

    【解决方案2】:

    当你比较时

    double sum1 = std::accumulate(tmpObj.get_skills().begin(), tmpObj.get_skills().end(), 0.,
                                  [](const string &s, const double &sum)
                                      { return s.size() + sum; });
    

    std::accumulate - Parameters

    操作 - ...
    Ret fun(const Type1 &a, const Type2 &b);

    Type1 - T
    Type2 - 迭代器


    可以看到,二元运算符的第一个参数必须对应返回类型(double, sum),第二个运算符必须对应容器的类型(std::string),例如

    [](double sum, const std::string &s) { return sum + s.size(); }
    

    这也是编译器抱怨的原因

    没有从 'double' 到 'const std::__cxx11::string' 的已知转换

    它不能将 sum(一个 double)转换为 lambda 的第一个参数(一个字符串)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2010-09-14
      • 2021-10-04
      • 2021-10-14
      • 2011-09-12
      • 1970-01-01
      • 2015-03-10
      相关资源
      最近更新 更多