String C++;11:如何使用累积/lambda函数从字符串向量计算所有大小的总和?

String C++;11:如何使用累积/lambda函数从字符串向量计算所有大小的总和?,string,c++11,vector,lambda,accumulate,String,C++11,Vector,Lambda,Accumulate,对于字符串向量,返回每个字符串大小的总和 我试着使用累加和lambda函数(这是计算我想要的单线数的最好方法吗?) 代码写在方框()中 #包括 #包括 #包括 #包括 使用名称空间std; int main(){ 向量v={“abc”,“def”,“ghi”}; size_t totalSize=累计(v.begin(),v.end(),[](字符串s){返回s.size();}); cout这是因为您没有正确使用std::acculate。也就是说,您1)没有指定初始值,2)提供了一元谓词而不

对于字符串向量,返回每个字符串大小的总和

我试着使用累加和lambda函数(这是计算我想要的单线数的最好方法吗?)

代码写在方框()中

#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
向量v={“abc”,“def”,“ghi”};
size_t totalSize=累计(v.begin(),v.end(),[](字符串s){返回s.size();});

cout这是因为您没有正确使用
std::acculate
。也就是说,您1)没有指定初始值,2)提供了一元谓词而不是二进制谓词。请检查

写下你想要的东西的正确方法是:

#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
向量v={“abc”,“def”,“ghi”};
size\u t totalSize=累计(v.开始(),v.结束(),0,
[](size_t sum,const std::string&str){return sum+str.size();});
库特
#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;
}