chapter16_8.cpp
#include <iostream>
#include <vector>
#include <string>
struct Review{
std::string title;
int rating;
};
bool FillReview(Review& rr); //判断是否填入了书名以及评分,引用传入,传出布尔值
void ShowReview(const Review& rr); //展示输入的内容,引用传入,不传出值
int main(){
using std::cout;
using std::vector;
vector<Review> books; //声明一个vector,类型为Review,名称为books
Review temp; //声明一个类型为Review的变量temp
while(FillReview(temp)) //填入书名及评分,然后判断是否填入了书名以及评分,如果填入,下一步把temp放入books的vector
books.push_back(temp);
int num = books.size(); //判断容器的大小,单位是books的个数
if(num>0){
cout << "Thank you. You enter the following:\n" << "Rating\tBook\n";
for(int i = 0; i < num; i++)
ShowReview(books[i]); //books是一个vector,这里使用数组的方式调用vector里面的元素
cout << "Reprising:\n" << "Rating\tBook\n";
vector<Review>::iterator pr; //定义一个指向Review容器的迭代器pr,相当于一个指针
for(pr = books.begin(); pr != books.end(); pr++) //首先使迭代器指向vector的起始位置,然后遍历books容器中的内容
ShowReview(*pr); //展示vector里当前迭代器指向的book,这里要对指针解引用!!!
//因为指针是一个地址,解引用以后才是指针指向的值,这样就和上面的temp引用传入保持一致了
vector<Review> oldlist(books); //新建一个vector,名称为oldlist,内容为前一个vector的内容books,后面insert的时候要用到
if(num>3){ //如果books的num>3,执行下属操作
books.erase(books.begin()+1, books.begin()+3); //擦除books里第2个和第3个元素,注意第二个参数为超尾元素!!!!!!
cout << "After erasure:\n";
for(pr = books.begin(); pr != books.end(); pr++) //再次遍历books
ShowReview(*pr); //展示books
books.insert(books.begin(), oldlist.begin() + 1, oldlist.begin() + 2);
//把刚刚存入oldlist中的第2个元素存入books的起始位置,注意第三个参数是超尾元素!!!!!!
cout << "After insertion:\n";
for(pr = books.begin(); pr != books.end(); pr++) //遍历books
ShowReview(*pr);
}
books.swap(oldlist); //把books和oldlist的内容交换
cout << "Swapping oldlist with books:\n";
for (pr = books.begin(); pr != books.end(); pr++)
ShowReview(*pr);
}
else
cout << "Nothing entered, nothing gained.\n";
return 0;
}
bool FillReview(Review& rr)
{
std::cout << "Enter book title (quit to quit): ";
std::getline(std::cin, rr.title); //从键盘输入整行数据并把行尾的换行符丢弃discard,并存入rr.title中
if(rr.title == "quit") //判断读取的数据是否等于quit,如果是,返回false
return false;
std::cout << "Enter book rating: ";
std::cin >> rr.rating; //读取rating
if(!std::cin) //如果没有输入rating,返回false
return false;
while (std::cin.get() != '\n') //若没有读取到换行符,依旧返回false
continue;
return true;
}
void ShowReview(const Review& rr)
{
std::cout << rr.rating << "\t" << rr.title << std::endl; //引用传入了rr,这里的rr是由指针解引用,然后&取地址得到的
}