word_freq.cc revision f4752293
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 178107c90fSShuo Chen std::vector<std::pair<int, WordCount::const_iterator>> freq; 18144e8e4eSShuo Chen freq.reserve(counts.size()); 198107c90fSShuo Chen for (auto it = counts.cbegin(); it != counts.cend(); ++it) 20144e8e4eSShuo Chen { 21144e8e4eSShuo Chen freq.push_back(make_pair(it->second, it)); 22144e8e4eSShuo Chen } 23144e8e4eSShuo Chen 24f4752293SShuo Chen std::sort(freq.begin(), freq.end(), [](const std::pair<int, WordCount::const_iterator>& lhs, // const auto& lhs in C++14 25f4752293SShuo Chen const std::pair<int, WordCount::const_iterator>& rhs) { 26144e8e4eSShuo Chen return lhs.first > rhs.first; 27144e8e4eSShuo Chen }); 28144e8e4eSShuo Chen // printf("%zd\n", sizeof(freq[0])); 29144e8e4eSShuo Chen for (auto item : freq) 30144e8e4eSShuo Chen { 31144e8e4eSShuo Chen std::cout << item.first << '\t' << item.second->first << '\n'; 32144e8e4eSShuo Chen } 33144e8e4eSShuo Chen} 34