Created
January 12, 2013 19:03
-
-
Save chenshuo/4519962 to your computer and use it in GitHub Desktop.
sort words by frequencies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <unordered_map> | |
#include <vector> | |
typedef std::unordered_map<std::string, int> WordCount; | |
struct Greater | |
{ | |
bool operator()(const std::pair<int, WordCount::iterator>& lhs, | |
const std::pair<int, WordCount::iterator>& rhs) const | |
{ | |
return lhs.first > rhs.first; | |
} | |
}; | |
int main() | |
{ | |
WordCount counts; | |
std::string word; | |
while (std::cin >> word) | |
{ | |
counts[word]++; | |
} | |
typedef std::vector<std::pair<int, WordCount::iterator> > FreqList; | |
FreqList freq; | |
freq.reserve(counts.size()); | |
for (WordCount::iterator it = counts.begin(); it != counts.end(); ++it) | |
{ | |
freq.push_back(make_pair(it->second, it)); | |
} | |
std::sort(freq.begin(), freq.end(), Greater()); | |
for (auto item : freq) | |
{ | |
std::cout << item.first << '\t' << item.second->first << '\n'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment