STL Examples

Example 1

Reading from standard input, print out the frequency of each distinct word. #include <iostream> #include <map> #include <string> using std::string; using std::cin; using std::cout; using std::endl; int main() { std::map<string, int> count; string s; while (cin >> s) ++count[s]; std::map<string, int>::iterator it; for (it = count.begin(); it != count.end(); ++it) cout << it->second << "\t" << it->first << endl; }

Example 2

Reading from standard input, print out all the words read in reverse alphabetical order. #include <iostream> #include <algorithm> #include <vector> #include <string> using std::string; using std::cin; using std::cout; using std::endl; using std::copy; struct reverse_order { bool operator()(const string & a, const string & b) { return !(a < b); } }; int main() { std::vector<string> v; string s; copy(std::istream_iterator<string>(cin), std::istream_iterator<string>(), std::back_inserter(v)); std::sort(v.begin(), v.end(), reverse_order()); copy(v.begin(), v.end(), std::ostream_iterator<string>(cout, "\n")); }

Challenge

Using ideas from the examples above, write a program that determines what the fifth most frequent word is in the text of Hamlet.

Hint: Your program should not be more than about 5-10 lines longer than the first example above.


Go Back Home