Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So while it's trivial to find the amount of characters that are inside of a vector of std::string, I was wondering if there's a way to use the STL to do all of the work for you instead of having two for loops, one to loop through the vector and another to loop through the string in each index of the vector.

I've tried using other STL functions (such as attempting to use std::for_each in a few unique ways), but all of my attempts have resulted in no success.

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?

}
like image 738
Tundra Fizz Avatar asked Dec 11 '22 12:12

Tundra Fizz


1 Answers

To start, you do not need the second loop:

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

Now for the Standard Library solution:

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

Here is a demo on ideone.

like image 143
Sergey Kalinichenko Avatar answered Jan 18 '23 23:01

Sergey Kalinichenko