fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <cctype>
  4. #include <map>
  5.  
  6. // utility function for converting a string to lower case.
  7. std::string as_lower(const std::string& text)
  8. {
  9. std::string result;
  10.  
  11. for (auto letter : text)
  12. result += static_cast<char>(std::tolower(letter));
  13.  
  14. return result;
  15. }
  16.  
  17. int main()
  18. {
  19. // a map is an associative container. In this case a word whose type is
  20. // std::string is associated with a count whose type is unsigned
  21. // http://w...content-available-to-author-only...s.com/reference/map/map/
  22. std::map<std::string, unsigned> words;
  23.  
  24. // using the words["word"] notation will cause an entry to be created for
  25. // "word" if one doesn't already exist, with a count of 0. Whether it did
  26. // or didn't exist prior to that call, a reference to the count will be
  27. // returned.
  28. // http://w...content-available-to-author-only...s.com/reference/map/map/operator%5B%5D/
  29.  
  30. std::string word;
  31. while (std::cin >> word) // while a word is succesfully extracted,
  32. words[as_lower(word)]++; // increase the count associated with it.
  33.  
  34.  
  35. // print the words and associated counts:
  36. for (auto& w : words)
  37. std::cout << '"' << w.first << "\": " << w.second << '\n';
  38. }
Success #stdin #stdout 0s 3436KB
stdin
I ate a pie
It was a blueberry pie
I really like pie
Pie is good
I like good pie
stdout
"a": 2
"ate": 1
"blueberry": 1
"good": 2
"i": 3
"is": 1
"it": 1
"like": 2
"pie": 5
"really": 1
"was": 1