#include<iostream> #include<map> using namespace std; class WordCount { private: public: string word; int count; WordCount() { word = ""; count = 1; } WordCount(string s) { word = s; count = 1; } }; int main(int argc, char *argv[]) { // key is a word (string), data is a count (int) map<string, WordCount> bst; map<string, WordCount>::iterator it; // read input, insert words into bst string s; while (cin >> s) { it = bst.find(s); if (it == bst.end()) { // could have done this instead - //if (bst.count(s) == 0) // insert word s into the bst with count of 1 WordCount w(s); bst.insert(pair<string, WordCount>(s, w)); } else { it->second ++ ; // could have done this instead - //bst.at(s) ++; } } // declare a bst to store the same info but now sorted by count map<int, WordCount> bst_byCount; map<int, WordCount>::iterator it2; // insert everything from bst into bst_byCount for (it=bst.begin(); it!=bst.end(); ++it) { //cout << it->first << " => " << it->second.count << '\n'; bst_byCount.insert(pair<int, WordCount>(it->second.count, it->second)); } // print bst_byCount for (it2=bst_byCount.begin(); it2!=bst_byCount.end(); ++it2) { cout << it2->second.word << " => " << it2->second.count << '\n'; } asdfjklhasdklfhasdkljf; return 0; }