首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C++11:如何使用累加/λ函数从字符串的向量计算所有大小的总和?

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

Stack Overflow用户
提问于 2019-05-20 00:05:12
回答 1查看 1.3K关注 0票数 1

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

我试着使用累加和一个lambda函数(这是在单行中计算我想要的值的最佳方法吗?)

代码写在wandbox (https://wandbox.org/permlink/YAqXGiwxuGVZkDPT)中

代码语言:javascript
复制
#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派生出来的;

我想知道如何修复我的代码?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-20 00:13:37

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

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

代码语言:javascript
复制
#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;
}

这两个问题都在下面的代码中得到了修复:

  1. 0被指定为初始值,因为std::accumulate需要知道从哪里开始,而
  2. 现在接受两个参数:累加值和下一个元素。

还要注意const ref是如何将std::string传递给lambda的,而您是通过值传递它的,这导致在每次调用时都会复制字符串,这并不酷

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56209611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档