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?
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With