word_freq.cc revision 144e8e4e
1144e8e4eSShuo Chen#include <algorithm> 2144e8e4eSShuo Chen#include <iostream> 3144e8e4eSShuo Chen#include <unordered_map> 4144e8e4eSShuo Chen#include <vector> 5144e8e4eSShuo Chen 6144e8e4eSShuo Chentypedef std::unordered_map<std::string, int> WordCount; 7144e8e4eSShuo Chen 8144e8e4eSShuo Chenint main() 9144e8e4eSShuo Chen{ 10144e8e4eSShuo Chen WordCount counts; 11144e8e4eSShuo Chen std::string word; 12144e8e4eSShuo Chen while (std::cin >> word) 13144e8e4eSShuo Chen { 14144e8e4eSShuo Chen counts[word]++; 15144e8e4eSShuo Chen } 16144e8e4eSShuo Chen 17144e8e4eSShuo Chen std::vector<std::pair<int, WordCount::iterator>> freq; 18144e8e4eSShuo Chen freq.reserve(counts.size()); 19144e8e4eSShuo Chen for (WordCount::iterator it = counts.begin(); it != counts.end(); ++it) 20144e8e4eSShuo Chen { 21144e8e4eSShuo Chen freq.push_back(make_pair(it->second, it)); 22144e8e4eSShuo Chen } 23144e8e4eSShuo Chen 24144e8e4eSShuo Chen std::sort(freq.begin(), freq.end(), [](const auto& lhs, const auto& rhs) { 25144e8e4eSShuo Chen return lhs.first > rhs.first; 26144e8e4eSShuo Chen }); 27144e8e4eSShuo Chen // printf("%zd\n", sizeof(freq[0])); 28144e8e4eSShuo Chen for (auto item : freq) 29144e8e4eSShuo Chen { 30144e8e4eSShuo Chen std::cout << item.first << '\t' << item.second->first << '\n'; 31144e8e4eSShuo Chen } 32144e8e4eSShuo Chen} 33