allword3.cc From Astrachan pp 386-389 -------------------------------------- #include #include #include // for exit #include "CPstring.h" #include "vector.h" #include "prompt.h" #include "ctimer.h" // author: Owen Astrachan // // lists all words in an input file, but avoids duplicates // uses class WordList to encapsulate behavior // // 5-15-95 class WordList { public: WordList(int size); // constructor, specify size of list void Update(const string & word); // update occurrences of word int GetUnique(); // return # of unique words in list int GetTotal(); // return # of total words in list void Print(); // print all words in list private: int myCount; // # of entries stored in myList int mySize; // capacity of myList int myTotal; // # of words (non-unique) Vector myList; // storage for strings int Search(const string & key); // returns index in myList of key }; WordList::WordList(int size) : myCount(0), mySize(size), myTotal(0), myList(size) { // all work done in initializer list } int WordList::Search(const string & key) // postcondition: returns index at which key occurs in myList // returns -1 if key does not occur { int k; for(k=0; k < myCount; k++) { if (myList[k] == key) // found key in list { return k; } } return -1; } void WordList::Update(const string & word) // postcondition: updates occurrence of word // adds word to list if not already present // increments count of total # of words { int loc = Search(word); myTotal++; if (loc == -1) // not already in list { if (myCount >= mySize) { mySize *= 2; myList.SetSize(mySize); } myList[myCount] = word; myCount++; } } void WordList::Print() // postcondition: all elements of myList printed { int k; for(k=0; k < myCount; k++) { cout << myList[k] << endl; } cout << endl << "# of words = " << myCount << endl; } int WordList::GetUnique() // postcondition: returns # unique words in list { return myCount; } int WordList::GetTotal() // postcondition: returns total # of words in list // same as # of times Update called { return myTotal; } int main() { string word; // word read from file string filename = PromptString("enter name of file: "); ifstream input; WordList wlist(5000); CTimer timer; input.open(filename); if (input.fail()) { cout << "could not open file " << filename << endl; exit(0); } while (input >> word) // reading word succeeded { timer.Start(); wlist.Update(word.Downcase()); timer.Stop(); } wlist.Print(); cout << "total words (non-unique): " << wlist.GetTotal() << endl; cout << "total time for update = " << timer.CumulativeTime() << endl; return 0; } Sample output: allword3 enter name of file: honor duke university undergraduate honor code its ... engineering when observe committed violation this code. # of words = 112 total words (non-unique): 192 total time for update = 0.03