fork download
  1. #include <vector>
  2. #include <string>
  3. #include <iostream>
  4.  
  5. int main(void)
  6. {
  7. int chars = 0;
  8. std::vector<std::string> str;
  9. str.push_back("Vector");
  10. str.push_back("of");
  11. str.push_back("four");
  12. str.push_back("words");
  13.  
  14. for(int i = 0; i < str.size(); ++i)
  15. for(int j = 0; j < str[i].size(); ++j)
  16. ++chars;
  17. std::cout << "Number of characters: " << chars << std::endl; // 17 characters
  18.  
  19. chars=0;
  20. for(int i = 0; i < str.size(); ++i)
  21. chars+=str[i].size();
  22. std::cout << "Number of characters: " << chars << std::endl; // 17 characters
  23.  
  24. chars=0;
  25. for(auto i : str)
  26. chars+=i.size();
  27. std::cout << "Number of characters: " << chars << std::endl; // 17 characters
  28.  
  29. // Are there any STL methods that allows me to find 'chars'
  30. // without needing to write multiple for loops?
  31.  
  32. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Number of characters: 17
Number of characters: 17
Number of characters: 17