// File; ListFunctions.cpp // Read a file into a vector // Then, use a functor or two to perform list functions // Prepared by Dr. Spiegel #include #include #include #include #include #include using namespace std; // Functor for printing; its state keeps track of items printed template struct print : public unary_function { print(ostream& out) : os(out), count(0) {} void operator() (T x) { os << x << ' '; ++count; } ostream& os; int count; }; // Functor for counting occurrences of a letter template struct countOccurrences : public unary_function { countOccurrences(char key) : count(0), searchKey(key) {} void operator() (T1 elt) { count += ( elt.find(searchKey) < elt.size() ? 1 : 0); } int count; char searchKey; }; char menu(); void readWords(istream &in,vector &WList); int main() { vector TheWords; string fileName; cout << "Enter Input File >"; cin >> fileName; ifstream infile(fileName.c_str()); readWords(infile,TheWords); char choice; do { choice=toupper(menu()); if (choice=='P') { print P = for_each(TheWords.begin(), TheWords.end(), print(cout)); cout << endl << P.count << " objects printed." << endl; } else if (choice=='F') { // This doesn't work! Why not! Hint: Check STL documentation! vector::iterator it= max_element(TheWords.begin(),TheWords.end()); if (it!=TheWords.end()) cout << "Greatest Word is: " << *it << endl; } else if (choice=='W') { cout << "Words with Letter: Enter Letter >"; char let; cin >> let; countOccurrences CO = for_each(TheWords.begin(), TheWords.end(), countOccurrences(let)); cout << "There were " << CO.count << " words containing " << let << endl; } // else } while (toupper(choice)!='Q'); } char menu() { cout << "Choice:\n"; cout << "P)rint\n"; cout << "W)ords With a Letter\n"; cout << "F)ind Last Word Alphabetically\n"; cout << "Q)uit\n"; char response; cin >> response; return(response); } void readWords(istream &in,vector &WList) { string word; while (in >> word) WList.push_back(word); }