How to use STL to count characters in a std :: string vector?

So, although it is trivial to find the number of characters that are inside the std :: string vector, I was wondering if there is a way to use STL to do all the work for you, and not for two loops, skip one through the vector and the other through the string in each vector index.

I tried using other STL functions (for example, trying to use std :: for_each in several unique ways), but all my attempts did not lead to 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? } 
+4
source share
3 answers

First you don’t need a second loop:

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

Now to solve the standard library:

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

Here is the daemon on ideone .

+5
source

For a clear solution, you can use 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(); } ); 
+5
source
 int chars = accumulate(str.begin(), str.end(), 0, [](int sum, const string& elem) { return sum + elem.size(); }); 
+1
source

Source: https://habr.com/ru/post/1493083/


All Articles