#include <iostream>
#include <string>
#include <vector>
struct Review{
std::string title;
int rating;
};
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) //rating输入的是非数字时返回false
return false;
std::cin.get(); //接收换行符
return true;
}
void ShowReview(const Review &rr)
{
std::cout<<rr.rating<<"\t"<<rr.title<<std::endl;
}
int main()
{
using std::cout;
using std::vector;
vector<Review> books;//vector模板使用动态内存分配
Review temp;
while(FillReview(temp))
books.push_back(temp);//将元素添加到矢量尾
int num = books.size();//返回books的大小
if(num>0)
{
cout<<"Thank you. You entered the following:\n"
<<"Rating\tBooks\n";
vector<Review>::iterator pr;//为vector的Review类型规范声明一个迭代器(指针),作用域为整个类
for(pr=books.begin();pr != books.end();pr++)/*begin()返回books[o]的地址,end()返回最后一个元素后面的那个 元素的地址*/
ShowReview(*pr);
vector<Review> oldlist(books);
if(num>3)
{
//Remove two items
books.erase(books.begin()+1,books.begin()+3);/*erase()删除矢量中给定区间的元素,这里删除的是元素books[1]和books[2] ,注意范围*/
cout<<"After erasure:\n";
for(pr=books.begin();pr != books.end();pr++)
ShowReview(*pr);
//insert 1 item
books.insert(books.begin(),oldlist.begin()+1,oldlist.begin()+2);//insert()功能和erase()相反
cout<<"After insertion:\n";
for(pr=books.begin();pr != books.end();pr++)
ShowReview(*pr);
}
books.swap(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;
}