fork download
  1. /** Count words.
  2.  
  3.   One word per line.
  4.   Print the most frequent words and their counts first.
  5.  
  6.   To try:
  7.  
  8.   $ g++ -std=c++11 count-words.cpp && ./a.out <input
  9.   One 3
  10.   Three 1
  11.   Two 1
  12.  
  13. */
  14. #include <algorithm> // sort
  15. #include <iostream>
  16. #include <unordered_map>
  17. #include <utility> // pair
  18. #include <iterator> // begin
  19. #include <vector>
  20.  
  21. int main() {
  22. using namespace std;
  23. unordered_map<string, size_t> counter;
  24. string line;
  25. getline(cin, line); // read n and ignore it
  26. while(getline(cin, line)) // count words
  27. ++counter[line];
  28.  
  29. if (!cin.eof())
  30. return 1; // I/O error
  31.  
  32. // print the most frequent words first
  33. typedef pair<string,size_t> Pair;
  34. vector<Pair> v(begin(counter), end(counter));
  35. sort(begin(v), end(v), [](const Pair& a, const Pair& b) {
  36. return a.second > b.second;
  37. });
  38. for (const auto& p : v)
  39. cout << p.first << " " << p.second << endl;
  40. }
Success #stdin #stdout 0s 3440KB
stdin
5
One
Two
Three
One
One
stdout
One 3
Three 1
Two 1