请按如下方式修改下面的程序:
// vect3.cpp -- using STL functions #include <iostream> #include <string> #include <algorithm>
struct Review { std::string title; int rating; };
bool operator<(const Review & r1, const Review & r2); bool worseThan(const Review & r1, const Review & r2); bool FillReview(Review & rr); void ShowReview(const Review & rr); int main() { using namespace std;
vector<Review> books; Review temp; while (FillReview(temp)) books.push_back(temp); if (books.size() > 0) { cout << "Thank you. You entered the following " << books.size() << " rating:\n" << "Rating\tBook\n"; for_each(books.begin(), books.end(), ShowReview);
sort(books.begin(), books.end()); cout << "Sorted by title:\nRating\tBook\n"; for_each(books.begin(), books.end(), ShowRevied);
sort(books.begin(), books.end(), worseThan); cout << "Sorted by rating:\nrating\tBook\n"; for_each(books.begin(), books.end(), ShowReview);
random_shuffle(books.begin(), books.end()); cout << "After shuffling:nRating\tBook\n"; for_each(books.begin(), books.end(), ShowReview); } else cout << "No entries. "; cout << "Bye.\n"; return 0; }
bool operator<(const Review & r1, const Review & r2) { if (r1.title < r2.title) return true; else if (r1.title == r2.title && r1.rating < r2.rating) return true; else return false; }
bool worseThan(const Review & r1, const Review & r2) { if (r1.rating < r2.rating) return true; else return false; }
bool FillReview(Review & rr) { std::cout << "Enter book title (quit to quit): "; std::getline(std::cin,rr.title); if (rr.title == "quit") return false; std::cout << "Enter book rating: "; std::cin >> rr.rating; if (!std::cin) return false; // get rid of rest of input line while (std::cin.get() != '\n') continue; return ture; }
void ShowReview(const Review & rr) { std::cout << rr.rating << "\t" << rr.title << std::endl; }
修改方式如下:
a. 在结构Review中添加成员price。
b. 不使用vector<Review>来存储输入,而使用vector<shared_ptr<Review>>。别忘了,必须使用new返回的指针来初始化shared_ptr。
c. 在输入阶段结束后,使用一个循环让用户选择如下方法之一显示书籍:按原始顺序显示、按字母表顺序显示、按评级升序显示、按评级降序显示、按价格升序显示、按价格降序显示、退出。
下面是一种可能的解决方案:获取输入后,再创建一个shared_ptr矢量,并用原始数组初始化它。定义一个对指向结构的指针进行比较的operator<()函数,并使用它对第二个矢量进行排序,让其中的shared_ptr按其指向的对象中的书名排序。重复上述过程,创建按rating和price排序的shared_ptr矢量。请注意,通过使用rbegin()和rend(),可避免创建按相反的顺序排列的shared_ptr矢量。