一种使用STL计算std :: string向量中的字符的方法?

Tun*_*izz 4 c++ performance stl vector

因此,虽然找到std :: string向量中的字符数量是微不足道的,但我想知道是否有一种方法可以使用STL为您完成所有工作,而不是有两个for循环,一个到循环遍历向量,另一个循环遍历向量的每个索引中的字符串.

我尝试过使用其他STL函数(例如尝试以几种独特的方式使用std :: for_each),但我的所有尝试都没有成功.

int main(void)
{
  int chars = 0;
  std::vector<std::string> str;
  str.push_back("Vector");
  str.push_back("of");
  str.push_back("four");
  str.push_back("words");

  for(int i = 0; i < str.size(); ++i)
    for(int j = 0; j < str[i].size(); ++j)
      ++chars;

  std::cout << "Number of characters: " << chars; // 17 characters

  // Are there any STL methods that allows me to find 'chars'
  // without needing to write multiple for loops?

}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 6

首先,您不需要第二个循环:

for(int i = 0; i < str.size(); ++i) {
    chars += str[i].size();
}
Run Code Online (Sandbox Code Playgroud)

现在为标准库解决方案:

int chars = accumulate(str.begin(), str.end(), 0, [](int sum, const string& elem) {
    return sum + elem.size();
});
Run Code Online (Sandbox Code Playgroud)

这是关于ideone演示.


chr*_*ris 5

对于明确的解决方案,您可以使用std::accumulate:

using type = std::string::size_type;
type chars = std::accumulate(
    std::begin(str), std::end(str), type(0), [](type total, const std::string &s) {
        return total + s.length();
    }
);
Run Code Online (Sandbox Code Playgroud)