c++ - A way to use the STL to count chars in a vector of std::string? -
so while it's trivial find amount of characters inside of vector of std::string, wondering if there's way use stl of work instead of having 2 loops, 1 loop through vector , loop through string in each index of vector.
i've tried using other stl functions (such attempting use std::for_each in few unique ways), of 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 = 0; < str.size(); ++i) for(int j = 0; j < str[i].size(); ++j) ++chars; std::cout << "number of characters: " << chars; // 17 characters // there stl methods allows me find 'chars' // without needing write multiple loops? }
to start, not need second loop:
for(int = 0; < str.size(); ++i) { chars += str[i].size(); }
now standard library solution:
int chars = accumulate(str.begin(), str.end(), 0, [](int sum, const string& elem) { return sum + elem.size(); });
here demo on ideone.
Comments
Post a Comment