usealgo.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //usealgo.cpp -- using several STL elements
  2. #include <iostream>
  3. #include <string>
  4. #include <vector>
  5. #include <set>
  6. #include <map>
  7. #include <iterator>
  8. #include <algorithm>
  9. #include <cctype>
  10. using namespace std;
  11. char toLower(char ch) { return tolower(ch); }
  12. string & ToLower(string & st);
  13. void display(const string & s);
  14. int main()
  15. {
  16. vector<string> words;
  17. cout << "Enter words (enter quit to quit):\n";
  18. string input;
  19. while (cin >> input && input != "quit")
  20. words.push_back(input);
  21. cout << "You entered the following words:\n";
  22. for_each(words.begin(), words.end(), display);
  23. cout << endl;
  24. // place words in set, converting to lowercase
  25. set<string> wordset;
  26. transform(words.begin(), words.end(),
  27. insert_iterator<set<string> > (wordset, wordset.begin()),
  28. ToLower);
  29. cout << "\nAlphabetic list of words:\n";
  30. for_each(wordset.begin(), wordset.end(), display);
  31. cout << endl;
  32. // place word and frequency in map
  33. map<string, int> wordmap;
  34. set<string>::iterator si;
  35. for (si = wordset.begin(); si != wordset.end(); si++)
  36. wordmap[*si] = count(words.begin(), words.end(), *si);
  37. // display map contents
  38. cout << "\nWord frequency:\n";
  39. for (si = wordset.begin(); si != wordset.end(); si++)
  40. cout << *si << ": " << wordmap[*si] << endl;
  41. // cin.get();
  42. // cin.get();
  43. return 0;
  44. }
  45. string & ToLower(string & st)
  46. {
  47. transform(st.begin(), st.end(), st.begin(), toLower);
  48. return st;
  49. }
  50. void display(const string & s)
  51. {
  52. cout << s << " ";
  53. }