Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Templates Without Code Bloat


August 1995/Templates Without Code Bloat/Listing 4

Listing 4 A test program

 /*-------------------------------------------------------*
 * Simple program to test hashing.
 *
 * Problem: Read a list of words from stdin, count the
 *          frequency of each word and each letter.
 *-------------------------------------------------------*/

#include <iostream.h>
#include <iomanip.h>
#include <cstring.h>
#include "hashmap.h"

static unsigned
hash_str(const string &str)
{
    return str.hash();
}


static unsigned
hash_char(const char &theChar)
{
    return theChar;
}


static void
print_word(const string &word,
         int &count,
         void *out)
{
   (* (ostream *) out) << word << '\t' << count << endl;
}


static void
print_char(const char &ch, int &count, void *out)
{
   (* (ostream *) out) << ch << '\t' << count << endl;
}


int
main(int, char **)
{

   Map<string, int>  words(hash_str, 0);
   Map<char, int>    letters(hash_char, 0);

   string str;

   while (cin >> str) {
      ++words[str];
      for (int i = 0; i < str.length(); ++i)
          ++letters[str[i]];
   }

   cout << "\t\tWords:" << endl << endl;
   words.apply(print_word, &cout);
   cout << endl;

   cout << "\t\tLetters:" << endl << endl;
   letters.apply(print_char, &cout);
   cout << endl;

   return 0;
}
/* End of File */


Related Reading


More Insights