我找不到任何解决方案,所以我发布了一个新主题。我必须使用带有const函数的accumulate作为参数(为测试做一些练习(:
-
get_skills((-返回技能列表,定义为:
const vector<string>& get_skills() const;
-
我必须返回所有技能的长度总和
我尝试过的:
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"的已知转换
提前感谢!
如果不摆弄视图,您可以先转换为字符串长度,然后累加。视图会更好,但这很简单。
#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;
}
p.s.我应该补充一点,如果这样做,你也可以手动进行,但我想举一个例子,根据问题进行指责。
当您比较时
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-参数
操作
Ret fun(const Type1&a,const Type2&b(;
和
类型1-T
类型2-迭代器
您可以看到,二进制运算符的第一个参数必须对应于返回类型(double, sum
(,第二个运算符必须对应于容器的类型(std::string
(,例如
[](double sum, const std::string &s) { return sum + s.size(); }
这也是编译器抱怨的原因
从'double'到'const-std::__cxx11::string'没有已知的转换
它无法将sum(双精度(转换为lambda的第一个参数(字符串(。