/* allword3.cpp From Astrachan(1st) pp 386-389 */ #include #include //#include // for exit #include using namespace std; #include "tvector.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) tvector 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.resize(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.c_str()); if (input.fail()) { cout << "could not open file " << filename << endl; exit(0); } while (input >> word) // reading word succeeded { timer.Start(); wlist.Update(word); timer.Stop(); } wlist.Print(); cout << "total words (non-unique): " << wlist.GetTotal() << endl; cout << "total time for update = " << timer.CumulativeTime() << endl; return 0; } /* Sample output: prompt> allword3 enter name of file: gettysburg Gettysburg Address Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, dedicated to the proposition that all men are created equal. ... perish earth. Abraham Lincoln November 19, 1863 # of words = 163 total words (non-unique): 286 total time for update = 0 */