Listing 10
#include <regex> #include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <map> #include <string> using std::tr1::regex; using std::tr1::sregex_token_iterator; using std::map; using std::cout; using std::basic_ostream; using std::setw; using std::ostream_iterator; using std::string; using std::copy; string text = "The sun was warm but the wind was chill.\n" "You know how it is with an April day\n" "When the sun is out and the wind is still,\n" "You're one month on in the middle of May.\n" "But if you so much as dare to speak,\n" "A cloud comes over the sunlit arch,\n" "A wind comes off a frozen peak,\n" "And you're two months back in the middle of March.\n"; /* Robert Frost, from "Two Tramps in Mud Time" */ typedef map<string, int> counter; typedef counter::value_type pairs; namespace std { // add inserter to namespace std template <class Elem, class Alloc> basic_ostream<Elem, Alloc>& operator<<( basic_ostream<Elem, Alloc>& out, const pairs& val) { // insert pair<string, int> into stream return out << setw(6) << val.first << ": " << val.second; } } int main() { // count occurrences of each word regex word_sep("[ ,.\n]+"); sregex_token_iterator words(text.begin(), text.end(), word_sep, -1); sregex_token_iterator end; map<string, int> word_count; while (words != end) ++word_count[*words++]; copy(word_count.begin(), word_count.end(), ostream_iterator<pairs>(cout, "\n")); return 0; }