#include #include #include #include #include using namespace std; int main( int argc, char* argv[] ) { if ( argc != 2 ) { cerr << "USAGE: " << argv[0] << " filter-file\n"; return 1; } ifstream in_str( argv[1] ); if ( !in_str ) { cerr << "Couldn't open " << argv[1] << " for reading.\n"; return 1; } // create a map data structure without any values // -- i.e. just the keys (which'll be the filter-words) set filter_words; // keeps the set of keys sorted -- inserts/deletions/lookups are fast // -- and automatically deduplicate // -- e.g. the word "the" can only appear zero or one times string a_word; while ( in_str >> a_word ) { filter_words.insert( a_word ); // may or may not insert } cout << "FILTER WORDS:\n"; set::iterator p = filter_words.begin(); while ( p != filter_words.end() ) { cout << ' ' << *p; p++; } cout << endl; // for map and set: // insertions/deletions are O(log n) // lookups therefore O(log n) // // for set: // insert() // erase() // // const_iterator find( const Key& x ) const; // returns end() if not found // iterator lower_bound( const Key& x ); // iterator upper_bound( const Key& x ); // TO DO: use a set to create a hangman game // The map data structure is an associative container // that maps one data type to another (e.g. string to int) // e.g. map "the" to 140 "the" ==> 140 // e.g. map "Achilles" to 6 "Achilles" ==> 6 // key , value map< string, int > words; map< string, int >::iterator i; // other examples: // map< int, vector > m1; // maps int keys to vectors-of-strings // map< int, Word_Node > m2; // map< string, Word_Node > m3; // e.g. in the Word_Node class, we might // // have count, vector indexes, // // snippets // map< Student, vector > m4; string w; while ( cin >> w ) { // the key is specified in [key] // words[w] = words[w] + 1; // words[s]++; // the operator[] function is important i = words.find( w ); // do the lookup, but don't add it yet // if not found in the map if ( i == words.end() ) { if ( filter_words.find( w ) != filter_words.end() ) { // word is a filter-word, so skip it.... continue; } words.insert( make_pair( w, 1 ) ); #if 0 pair< map< string, int >::iterator, bool > p; p = words.insert( make_pair( w, 1 ) ); i = p.first; bool inserted = p.second; #endif } } // use an iterator to iterate through the elements of the map // and display them map< string, int >::const_iterator j = words.begin(); while ( j != words.end() ) { // key value cout << j->first << " (count: " << j->second << ")\n"; j++; } return 0; }