vect2.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // vect2.cpp -- methods and iterators
  2. #include <iostream>
  3. #include <string>
  4. #include <vector>
  5. struct Review {
  6. std::string title;
  7. int rating;
  8. };
  9. bool FillReview(Review & rr);
  10. void ShowReview(const Review & rr);
  11. int main()
  12. {
  13. using std::cout;
  14. using std::vector;
  15. vector<Review> books;
  16. Review temp;
  17. while (FillReview(temp))
  18. books.push_back(temp);
  19. int num = books.size();
  20. if (num > 0)
  21. {
  22. cout << "Thank you. You entered the following:\n"
  23. << "Rating\tBook\n";
  24. for (int i = 0; i < num; i++)
  25. ShowReview(books[i]);
  26. cout << "Reprising:\n"
  27. << "Rating\tBook\n";
  28. vector<Review>::iterator pr;
  29. for (pr = books.begin(); pr != books.end(); pr++)
  30. ShowReview(*pr);
  31. vector <Review> oldlist(books); // copy constructor used
  32. if (num > 3)
  33. {
  34. // remove 2 items
  35. books.erase(books.begin() + 1, books.begin() + 3);
  36. cout << "After erasure:\n";
  37. for (pr = books.begin(); pr != books.end(); pr++)
  38. ShowReview(*pr);
  39. // insert 1 item
  40. books.insert(books.begin(), oldlist.begin() + 1,
  41. oldlist.begin() + 2);
  42. cout << "After insertion:\n";
  43. for (pr = books.begin(); pr != books.end(); pr++)
  44. ShowReview(*pr);
  45. }
  46. books.swap(oldlist);
  47. cout << "Swapping oldlist with books:\n";
  48. for (pr = books.begin(); pr != books.end(); pr++)
  49. ShowReview(*pr);
  50. }
  51. else
  52. cout << "Nothing entered, nothing gained.\n";
  53. // std::cin.get();
  54. return 0;
  55. }
  56. bool FillReview(Review & rr)
  57. {
  58. std::cout << "Enter book title (quit to quit): ";
  59. std::getline(std::cin,rr.title);
  60. if (rr.title == "quit")
  61. return false;
  62. std::cout << "Enter book rating: ";
  63. std::cin >> rr.rating;
  64. if (!std::cin)
  65. return false;
  66. // get rid of rest of input line
  67. while (std::cin.get() != '\n')
  68. continue;
  69. return true;
  70. }
  71. void ShowReview(const Review & rr)
  72. {
  73. std::cout << rr.rating << "\t" << rr.title << std::endl;
  74. }