chapter16_9.cpp
#include <iostream>
#include <string>
#include <vector>
#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)) //当在review结构里插入了book,执行该循环
books.push_back(temp);
if (books.size() > 0) //只要插入了一本book,执行该循环,相对于前一个程序节省了一行代码,默认给size一个整型定义
{
cout << "Thank you. You entered the following "
<< books.size() << " ratings:\n" << "Rating\tBook\n"; //books是一个review结构的vector,每一个结构就是一个size
for_each(books.begin(), books.end(), ShowReview); //遍历begin和end之间的元素,ShowReview隐式接收一个迭代器参数,
//而且还对这个迭代器参数进行了解引用
sort(books.begin(), books.end()); //sort是对默认参数类型按照从小到大顺序排列的,对于新定义类型的排列,
//这里给出了操作符operator<的排序规则,按照books的title成员的字母顺序升序排列
//如果title的所有字母相同,则按照rating升序排列
cout << "Sorted by title:\nRating\tBook\n";
for_each(books.begin(), books.end(), ShowReview); //升序排列后展示
sort(books.begin(), books.end(), worseThan); //按rating升序排列
cout << "Sorted by rating:\nRating\tBooks\n";
for_each(books.begin(), books.end(), ShowReview); //按rating升序排列后展示,这里函数的接口都是引用传入,传入的参数都是隐式的迭代器参数
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;
while (std::cin.get() != '\n')
continue;
return true;
}
void ShowReview(const Review & rr)
{
std::cout << rr.rating << "\t" << rr.title << std::endl;
}