Wordcount in C++

#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <map> #include <locale> using std::cerr; using std::endl; template <typename Pair> bool greater_second(const Pair& p1, const Pair& p2) { return p1.second > p2.second; } std::locale loc(""); typedef std::vector<std::pair<std::string, int> > word_list; typedef std::map<std::string, int> word_map; static bool get_word(std::istream& input, std::string& word) { char c; while (input && input.get(c) && !std::isalpha(c, loc)); if (!input) { return false; } word.clear(); while (std::isalpha(c, loc)) { word.push_back(std::tolower(c, loc)); input.get(c); } input.putback(c); return true; } static void build_concordance(std::istream& input, word_map& concordance) { std::string word; while (get_word(input, word)) { ++concordance[word]; } } static void print_top_n(const word_list& list, int n) { for (word_list::const_iterator i = list.begin(); i != list.end() && i - list.begin() < n; ++i) { std::cout << (*i).first << " " << (*i).second << endl; } } int main(int argc, char const* const *argv) { if (argc < 2) { cerr << "Usage: " << argv[0] << " <file>" << endl; return 1; } if (argc > 2) { cerr << argv[0] << ": too many command-line arguments" << endl; return 1; } std::ifstream input; try { input.open(argv[1]); } catch (const std::exception& ex) { cerr << argv[0] << " unable to open " << argv[1] << endl; } word_map concordance; build_concordance(input, concordance); word_list list(concordance.begin(), concordance.end()); std::sort(list.begin(), list.end(), greater_second<word_map::value_type>); print_top_n(list, 10); return 0; }
Hosted by www.Geocities.ws

1