#include #include #include // for exit #include "apstring.h" #include "apvector.h" #include "systimer.h" // for SysTimer #include "prompt.h" #include "strutils.h" // for StripPunc and ToLower // author: Owen Astrachan // // lists all words in an input file, with word counts // // 5/28/97 const int NOT_FOUND = -1; struct WordStat { apstring info; // the apstring int count; // # of times apstring occurs }; int Search(const apvector & list, int numWords, const apstring & key) // precondition: numWords = # entries in list // postcondition: returns index at which key occurs in list // returns NOT_FOUND if key does not occur { int k; for(k=0; k < numWords; k++) { if (list[k].info == key) { return k; } } return NOT_FOUND; } void Update(apvector & list, int & numWords, const apstring & word) // precondition: numWords = # entries in list // postcondition: number of occurrences of word in list is updated // i.e., incremented by 1 or word is added to list { int location = Search(list,numWords,word); if (location != NOT_FOUND) { list[location].count++; } else { if (numWords >= list.length()) // grow if needed { list.resize(list.length() * 2); } list[numWords].info = word; list[numWords].count = 1; numWords++; } } void Print(const apvector & list, int numWords) // precondition: numWords = # entries in list // postcondition: all elements of list printed { int k; for(k=0; k < numWords; k++) { cout << list[k].count << "\t" << list[k].info << endl; } cout << endl << "# of words = " << numWords << endl; } int main() { apstring filename = PromptString("enter name of file: "); apstring word; // word read from file ifstream input; apvector list(1000); int numWords = 0; SysTimer timer; input.open(filename.c_str()); if (input.fail()) { cout << "could not open file " << filename << endl; exit(0); } while (input >> word) // reading word succeeded { ToLower(word); StripPunc(word); timer.start(); Update(list,numWords,word); timer.stop(); } Print(list,numWords); cout << "total time for update = " << timer.cumulativeTime() << endl; }