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

A way to use the STL to count chars in a vector of std::string?

本文关键字:向量 string 字符 方法 std 计算 一种 STL      更新时间:2023-10-16

因此,虽然查找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?
}

要开始,不需要第二个循环:

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

现在是标准库解决方案:

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

这是ideone上的演示。

对于意图明确的解决方案,可以使用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();
    }
);
int chars = accumulate(str.begin(), str.end(), 0, [](int sum, const string& elem) {
return sum + elem.size();
});