C++ Notes: Examples: Lefthand words 3

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
// -- lefthand3.cpp - Find longest word typed with left hand.
//    Fred Swartz - 2002-09-16

// Use set to save all words of longest length.
// Uses iterators or copy

#include <iostream>
#include <string>
#include <set>
using namespace std;

//--- prototypes
bool isOnlyLeftHand(string w);

//============================================================= main
int main() {
    string word;           // holds each input word
    set<string> maxWords;  // longest words
    int maxlen = 0;        // length of longest word

    while (cin >> word) {
        if (word.length() >= maxlen && isOnlyLeftHand(word)) {
            if (word.length() > maxlen) {
                maxlen = word.length(); // new max
                maxWords.clear();       // clear shorter words
            }
            maxWords.insert(word);  // remember this word
        }
    }

    cout << "Words of length " << maxlen << endl;

    set<string>::iterator pos;
    for (pos = maxWords.begin(); pos != maxWords.end(); ++pos) {
        cout << *pos << endl;
    }

    /* OR copy(maxWords.begin(), maxWords.end(),
         ostream_iterator<string>(cout, "\n")); */

    return 0;
}//end main


//=================================================== isOnlyLeftHand
bool isOnlyLeftHand(string w) {
    return w.find_first_not_of("qwertasdfgzxcvb") == string::npos;
}//end isOnlyLeftHand