/* * Standard containers, std::list, exercise 1. */ #include #include #include #include #include #include #include using namespace std; template ostream& operator<<(ostream& os, const list& v) { copy(begin(v), end(v), ostream_iterator(cout, " ")); return os; } template struct by_length { bool operator()(const T& arg1, const T& arg2) const { return arg1.size() < arg2.size(); } typedef bool result_type; typedef T first_argument_type; typedef T second_argument_type; }; template struct longer_than { bool operator()(const T& arg) { return size < arg.size(); } typedef bool result_type; typedef T argument_type; }; const list remove_word { "a", "and", "as", "be", "but", "do", "for", "if", "in", "is", "it", "its", "not", "of", "or", "that", "the", "to" }; int main(int argc, char* argv[]) { if (argc != 2) { cout << "usage: " << argv[0] << " \n"; return 1; } ifstream input(argv[1]); if (! input) { cout << argv[1] << ": could not open.\n"; return 2; } list words; copy(istream_iterator(input), istream_iterator(), back_inserter(words)); cout << "Words read:\n" << words << "\n\n"; words.sort(); cout << "After sorting:\n" << words << "\n\n"; words.erase(unique(begin(words), end(words)), end(words)); cout << "After removing duplicates:\n" << words << "\n\n"; words.sort(by_length()); // list::sort is stable cout << "After sorting by increasing length:\n" << words << "\n\n"; int n = count_if(begin(words), end(words), longer_than<5>()); cout << "The number of words longer than five letters is " << n << ".\n\n"; for (const auto& word : remove_word) { words.erase(remove(begin(words), end(words), word), end(words)); } cout << "After removing common words:\n" << words << "\n\n"; return 0; }