// Program to count the number of each word encountered // on the input stream. // // Output all words at the end: // the (count: 400) // of (count: 200) // algorithm (count: 3) // ... #include #include #include using namespace std; // create a separate class to store in the list: class Word_Node { public: string word; int count; // vector indexes; // where this word occurs // constructor Word_Node( const string& word ) { this->word = word; this->count = 1; } }; int main() { list< Word_Node > words; string w; while ( cin >> w ) // <-- this loops n times { // is word w already in the list? bool found = false; list< Word_Node >::iterator i = words.begin(); while ( !found && i != words.end() ) // <-- this loops up to n times { if ( i->word == w ) { found = true; i->count++; } i++; // 2 } // O(n ) // if word w is not in the list, create it and add it to the list if ( !found ) { Word_Node node( w ); words.push_back( node ); } } // one option to speed "search" up is to sort this lists here.... // display the results list< Word_Node >::iterator i; for ( i = words.begin() ; i != words.end() ; i++ ) { cout << i->word << " (count: " << i->count << ")\n"; } return 0; }