vect3.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // vect3.cpp -- using STL functions
  2. #include <iostream>
  3. #include <string>
  4. #include <vector>
  5. #include <algorithm>
  6. struct Review {
  7. std::string title;
  8. int rating;
  9. };
  10. bool operator<(const Review & r1, const Review & r2);
  11. bool worseThan(const Review & r1, const Review & r2);
  12. bool FillReview(Review & rr);
  13. void ShowReview(const Review & rr);
  14. int main()
  15. {
  16. using namespace std;
  17. vector<Review> books;
  18. Review temp;
  19. while (FillReview(temp))
  20. books.push_back(temp);
  21. if (books.size() > 0)
  22. {
  23. cout << "Thank you. You entered the following "
  24. << books.size() << " ratings:\n"
  25. << "Rating\tBook\n";
  26. for_each(books.begin(), books.end(), ShowReview);
  27. sort(books.begin(), books.end());
  28. cout << "Sorted by title:\nRating\tBook\n";
  29. for_each(books.begin(), books.end(), ShowReview);
  30. sort(books.begin(), books.end(), worseThan);
  31. cout << "Sorted by rating:\nRating\tBook\n";
  32. for_each(books.begin(), books.end(), ShowReview);
  33. random_shuffle(books.begin(), books.end());
  34. cout << "After shuffling:\nRating\tBook\n";
  35. for_each(books.begin(), books.end(), ShowReview);
  36. }
  37. else
  38. cout << "No entries. ";
  39. cout << "Bye.\n";
  40. // cin.get();
  41. return 0;
  42. }
  43. bool operator<(const Review & r1, const Review & r2)
  44. {
  45. if (r1.title < r2.title)
  46. return true;
  47. else if (r1.title == r2.title && r1.rating < r2.rating)
  48. return true;
  49. else
  50. return false;
  51. }
  52. bool worseThan(const Review & r1, const Review & r2)
  53. {
  54. if (r1.rating < r2.rating)
  55. return true;
  56. else
  57. return false;
  58. }
  59. bool FillReview(Review & rr)
  60. {
  61. std::cout << "Enter book title (quit to quit): ";
  62. std::getline(std::cin,rr.title);
  63. if (rr.title == "quit")
  64. return false;
  65. std::cout << "Enter book rating: ";
  66. std::cin >> rr.rating;
  67. if (!std::cin)
  68. return false;
  69. // get rid of rest of input line
  70. while (std::cin.get() != '\n')
  71. continue;
  72. return true;
  73. }
  74. void ShowReview(const Review & rr)
  75. {
  76. std::cout << rr.rating << "\t" << rr.title << std::endl;
  77. }