C++自学笔记_模拟读书_《C++ Primer》
#include <iostream> #include <set> #include <vector> #include <string> #include <cstdlib> using namespace std; /* 定义一个vector容器,存储在未来6个月里要阅读的数的名字, 定义一个set,用于记录已经看过的书名, 本程序支持从vector中选择一本没有读过的而现在要读的书, 并将该书名记录放入set中, 并且支持从已读数目set中删除该书的记录。 在虚拟的6个月后,输出已读数目和没读数目 */ int main() { vector<string> books; set<string> readedBooks; string name; //建立未来6个月未读的书名的vector对象 cout<<"Enter names for books you'd like to read:"<<endl; while(cin>>name){ books.push_back(name); } cin.clear(); bool timeOver=false; string answer,bookName; while(!timeOver&&!books.empty()){ //时间未到6个月且还有没读过的书 cout<<"Would you like to read a book?[Yes/No]"<<endl; cin>>answer; if(answer[0]=='Y'||answer[0]=='y'){ int i=rand()%books.size(); //产生一个伪随机数 bookName=books[i]; cout<<"you can read this book "<<bookName<<endl; readedBooks.insert(bookName); books.erase(books.begin()+i); //从books删除该书 cout<<"Did you read it?[Yes/No]"<<endl; cin>>answer; if(answer[0]=='N'||answer[0]=='n'){ set<string>::iterator iter1=readedBooks.find(bookName); readedBooks.erase(iter1); books.push_back(bookName); } } cout<<"Time Over?[Yes/No]"<<endl; cin>>answer; if(answer[0]=='Y'||answer[0]=='y'){ timeOver=true; //虚拟的6个月结束了 } } if(timeOver){ cout<<"books read:"<<endl; for(set<string>::iterator sit=readedBooks.begin();sit!=readedBooks.end();++sit){ cout<<*sit<<endl; } cout<<"books not read:"<<endl; for(vector<string>::iterator vit=books.begin();vit!=books.end();++vit){ cout<<*vit<<endl; } }else{ cout<<"you have read all these books!"<<endl; } return 0; }