对于字符串的向量,返回每个字符串的大小之和。
我试着使用累加和一个lambda函数(这是在单行中计算我想要的值的最佳方法吗?)
代码写在wandbox (https://wandbox.org/permlink/YAqXGiwxuGVZkDPT)中
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> v = {"abc", "def", "ghi"};
size_t totalSize = accumulate(v.begin(), v.end(), [](string s){return s.size();});
cout << totalSize << endl;
return 0;
}
我希望得到一个数字(9),但返回的是错误:
/opt/wandbox/gcc-head/include/c++/10.0.0/bits/stl_numeric.h:135:39:注意:'std::__cxx11::basic_string‘不是从'const __gnu_cxx::__normal_iterator<_Iterator,_Container>’135 | __init = _GLIBCXX_MOVE_IF_20(__init) +*__first派生出来的;
我想知道如何修复我的代码?谢谢。
发布于 2019-05-20 00:13:37
这是因为您没有正确使用std::accumulate
。也就是说,您1)没有指定初始值,2)提供了一元谓词而不是二元谓词。请查看the docs。
编写你想要的东西的正确方法是:
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> v = {"abc", "def", "ghi"};
size_t totalSize = accumulate(v.begin(), v.end(), 0,
[](size_t sum, const std::string& str){ return sum + str.size(); });
cout << totalSize << endl;
return 0;
}
这两个问题都在下面的代码中得到了修复:
0
被指定为初始值,因为std::accumulate
需要知道从哪里开始,而还要注意const ref是如何将std::string
传递给lambda的,而您是通过值传递它的,这导致在每次调用时都会复制字符串,这并不酷
https://stackoverflow.com/questions/56209611
复制相似问题