C.Primer.Plus(第六版)第16章 编程练习

来源:互联网 发布:出口退税算法 编辑:程序博客网 时间:2024/05/16 01:44
//16.1#include <iostream>#include <string>using namespace std;bool isPalindrome(const string &);int main(){cout<<"Please enter a string type data:";string str1;while(cin>>str1 && str1 != "quit"){for(int i=0;i<str1.length();++i){if(!islower(str1[i])){cout<<"The input must be a lowercase character,bye!"<<endl;return 0;}}isPalindrome(str1);cout<<"Please enter a string type data:";}}bool isPalindrome(const string & str){for(int i = 0,j = str.length()-1; i<=j;++i,--j)if(str[i] != str[j]){cout<<"the string dont't match Palindrome type,bye!"<<endl;return 0;}cout<<"Input string is a Palindrome number."<<endl;return 1;}
//16.2#include <iostream>#include <string>using namespace std;bool isPalindrome(const string &);int main(){cout<<"Please enter a string type data:";string str1;while(cin>>str1 && str1 != "quit"){string temp;for(int i=0;i<str1.length();++i){if(isalpha(str1[i]))temp.push_back(tolower(str1[i]));}str1 =temp;isPalindrome(str1);cout<<"Please enter a string type data:";}}bool isPalindrome(const string & str){for(int i = 0,j = str.length()-1; i<=j;++i,--j)if(str[i] != str[j]){cout<<"the string dont't match Palindrome type,bye!"<<endl;return 0;}cout<<"Input string is a Palindrome number."<<endl;return 1;}
//16.3// hangman.cpp#include <iostream>#include <fstream>#include <vector>#include <string>#include <cstdlib>#include <ctime>#include <cctype>using std::string;const int NUM = 26;int main(){using namespace std;std::srand(std::time(0));vector<std::string> str_arr;string temp;ifstream fopen;fopen.open("data.txt");if(!fopen.is_open()){cout<<"Could not open the data file"<<endl;exit(EXIT_FAILURE);}fopen>>temp;while(fopen.good()){str_arr.push_back(temp);fopen>>temp;}char play;cout<<"Will you play a word game? <y/n> ";cin>>play;play = tolower(play);while(play == 'y'){string target = str_arr[std::rand() % str_arr.size()];int length = target.length();string attempt(length,'-');string badchars;int guesses = 6;cout<<"Guess my secret word. It has "<<length<<" length, and you guess\n"<<"one letter at a time.You get "<<guesses<<" wrong guesses.\n";cout<<"Your word: "<<attempt<<endl;while(guesses > 0 && attempt != target){char letter;cout<<"Guess a letter: ";cin>>letter;if(badchars.find(letter) != string::npos || attempt.find(letter) !=string::npos){cout<<"You already guessed that. Try again.\n";continue;}int loc = target.find(letter);if(loc == string::npos){cout<<"Oh,bad guess!\n";--guesses;badchars += letter;}else{cout<<"Good guess!\n";attempt[loc] = letter;loc = target.find(letter,loc+1);while(loc != string::npos){attempt[loc] = letter;loc = target.find(letter,loc+1);}}cout<<"Your word: "<<attempt<<endl;if(attempt != target){if(badchars.length()>0)cout<<"Bad choices:"<<badchars<<endl;cout<<guesses<<"bad guesses left\n";}}if(guesses > 0)cout<<"That's right!\n";elsecout<<"Sorry,the word is "<<target<<".\n";cout<<"Will you plat another? <y/n>";cin>>play;play = tolower(play);}cout<<"Bye\n";return 0;}
//16.4#include <iostream>#include <vector>#include <algorithm>using namespace std;int reduce(long ar[],int n);bool compare(long a,long b){return a<b;//increase//return a>b;//decrease}int main(){long lo[6] = {2,3,44,3,3,2};int count = reduce(lo,6);for(int i = 0;i<count;++i)cout<<lo[i]<<" ";cout<<endl;}int reduce(long ar[],int n){vector<long> arr;for(int i = 0;i<n;i++)arr.push_back(ar[i]);sort(arr.begin(),arr.end(),compare);vector<long>::iterator new_end = unique(arr.begin(),arr.end());//将有效数据排序,将有效结尾存储下来arr.erase(new_end,arr.end());//删除多余的数据int count = 0;for(vector<long>::iterator temp = arr.begin();temp != arr.end();++temp)ar[count++] = (*temp);return count;}
//16.5#include <iostream>#include <string> //忘记定义string类...#include <vector>#include <algorithm>using namespace std;template <class T>int reduce(T ar[],int n);int main(){string test[6] = {"just","different","amazing","MDF","Magic","amazing"};int count = reduce(test,6);for(int i = 0;i<count;++i)cout<<test[i].c_str()<<" ";cout<<endl;long lo[6] = {2,3,44,3,3,2};int size = reduce(lo,6);for(int i = 0;i<size;++i)cout<<lo[i]<<" ";cout<<endl;return 0;}template <class T>int reduce(T ar[],int n){vector<T> arr;for(int i = 0;i<n;i++)arr.push_back(ar[i]);sort(arr.begin(),arr.end());vector<T>::iterator new_end = unique(arr.begin(),arr.end());//将有效数据排序,将有效结尾存储下来arr.erase(new_end,arr.end());//删除多余的数据int count = 0;for(vector<T>::iterator temp = arr.begin();temp != arr.end();++temp)ar[count++] = (*temp);return count;}
// 16.6  仅仅是简单的使用queue模板类的方法#include <iostream>#include <queue>#include <cstdlib>#include <ctime>const int MIN_PER_HR = 60;bool newcustomer(double x);class Customer{private:long arrive;// arrival time for customerint processtime;//processing time for customer 交易时间public:Customer(){arrive = processtime = 0;}void set(long when){processtime = std::rand() % 3 + 1;arrive = when;}long when() const {return arrive;}int ptime() const {return processtime;}};typedef Customer Item;int main(){using namespace std;std::srand(std::time(0));cout<<"Case Study:Bank of Heather Automatic Teller\n";cout<<"Enter maximum size of queue:";int qs;cin>>qs;queue<Item> line;//cout<<"Enter the number of simulation hours: ";int hours;cin>>hours;//测试时间// simulation will run 1 cycle per minutelong cyclelimit = MIN_PER_HR * hours;//循环次数cout<<"Enter the average number of customer per hour: ";double perhour;cin>>perhour;//一小时多少客户double min_per_cust;min_per_cust = MIN_PER_HR / perhour;//每分钟多少客户Item temp;// new customer data long turnaways = 0;//turned away by full queue 被拒绝的客户long customers = 0;//joined the queuelong served = 0;//served during the simulation  服务人数long sum_line = 0;//cumulative line lentgth 累计长度int wait_time = 0;//time until autoteller is freelong line_wait = 0;//cumulative time in linefor(int cycle = 0;cycle<cyclelimit;cycle++){if(newcustomer(min_per_cust))//有客户访问{if(line.size() == qs)//队列是否满员//turnaways++;else{customers++;temp.set(cycle);//将进队时的时间记录下来,用于记录在队列中的时间,以及操作时间line.push(temp);//入队//}}if(wait_time<=0 && !line.empty())//如果客户操作完成{line.pop();//出队并将指针指向新的头结点wait_time = temp.ptime();//得到被释放头结点的操作时间line_wait += cycle - temp.when();//从排队到开始操作的时间served++;}if(wait_time>0)wait_time--;sum_line += line.size();//}if(customers>0){cout<<"customers accepted: "<<customers<<endl;cout<<" customers served: "<<served<<endl;cout<<"    turnaways:"<<turnaways<<endl;cout<<"average queue size:";cout.precision(2);cout.setf(ios_base::fixed,ios_base::floatfield);cout<<(double)sum_line/cyclelimit <<endl;cout<<"average wait time: "<<(double)line_wait /served <<" minutes\n";}elsecout<<"No customers!\n";cout<<"Done!\n";return 0;}bool newcustomer(double x){return (std::rand() * x / RAND_MAX <1);}  
//16.7#include <iostream>#include <ctime>#include <vector>#include <algorithm>using namespace std;vector<int> lotto(int x,int y);int main(){srand(time(0));vector<int> winners;winners = lotto(51,6);for(int i =0;i<winners.size();i++)cout<<winners[i]<<" ";cout<<endl;}vector<int> lotto(int x, int y){vector<int> temp;vector<int> output;for(int i =0;i<x;++i)temp.push_back(i+1);for(int i =0;i<y;++i){random_shuffle(temp.begin(),temp.end());output.push_back(temp[0]);}return output;}
//16.8#include <iostream>#include <string>#include <list>#include <vector>#include <algorithm>#include <iterator>int main(){using namespace std;list<string> mat,pat;cout<<"please enter mat's friend list(\"quit\" to end):";string temp;while(cin>>temp && temp != "quit"){mat.push_back(temp);cout<<"please enter mat's friend list:";}cout<<"please enter pat's friend list(\"quit\" to end):";while(cin>>temp && temp != "quit"){pat.push_back(temp);cout<<"please enter pat's friend list(\"quit\" to end):";}mat.sort(),mat.unique();pat.sort(),pat.unique();for(list<string>::iterator it = mat.begin();it != mat.end();++it)cout<<(*it)<<" , ";cout<<endl;for(list<string>::iterator it = pat.begin();it != pat.end();++it)cout<<(*it)<<" , ";cout<<endl;vector<string> sum(pat.size()+mat.size());copy(mat.begin(),mat.end(),sum.begin());copy(pat.begin(),pat.end(),(sum.begin()+mat.size()));sort(sum.begin(),sum.end());vector<string>::iterator new_end = unique(sum.begin(),sum.end());sum.erase(new_end,sum.end());copy(sum.begin(),sum.end(),ostream_iterator<string>(cout," "));cout<<endl;return 0;}
//16.9#include <iostream>#include <vector>#include <list>#include <ctime>#include <algorithm>const int NUM = 100000;int main(){using namespace std;srand(time(0));vector<int> vi0(NUM);for(int i =0;i<vi0.size();++i)vi0[i]= rand() % 100 + 1;vector<int> vi(vi0);list<int> li(vi0.begin(),vi0.end());clock_t start = clock();sort(vi.begin(),vi.end());clock_t end = clock();cout<<"STL algorithm time cost is "<<(double)(end-start)/CLOCKS_PER_SEC<<endl;start = clock();li.sort();end = clock();cout<<"list member function time cost is"<<(double)(end-start)/CLOCKS_PER_SEC<<endl;copy(vi0.begin(),vi0.end(),li.begin());start = clock();copy(li.begin(),li.end(),vi.begin());sort(vi.begin(),vi.end());copy(vi.begin(),vi.end(),li.begin());end = clock();cout<<"Compromise method time cost is"<<(double)(end-start)/CLOCKS_PER_SEC<<endl;return 0;}
//16.10#include <iostream>#include <string>#include <vector>#include <algorithm>#include <memory>struct Review{std::string title;int rating;double price;};bool FillReview(Review & rr);bool operator<( const std::shared_ptr<Review> & r1,const std::shared_ptr<Review> & r2);bool showRating(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2);bool showPrice(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2);void ShowReview(const std::shared_ptr<Review> & rr);void Showmenu(); int main(){using namespace std;vector<shared_ptr<Review>> books;Review temp;while(FillReview(temp))books.push_back(shared_ptr<Review>(new Review(temp)));vector<shared_ptr<Review>> new_ord(books); //按照题目要求分别创建对应的shared_ptr对象sort(new_ord.begin(),new_ord.end()); //按字母排序vector<shared_ptr<Review>> new_pri(books);//按价格排序对象sort(new_pri.begin(),new_pri.end(),showPrice);vector<shared_ptr<Review>> new_rat(books);//按评分排序的对象sort(new_rat.begin(),new_rat.end(),showRating);if(books.size() > 0){cout<< "Thank you,You entered the following "              << books.size() << " ratings.\n";Showmenu();  char key;cin>>key;while(key != 'q'){cout<<"title\t"<<"rating\t"<<"price\n";switch(key){case'1':for_each(books.begin(),books.end(), ShowReview); break;              case'2': for_each(new_ord.begin(),new_ord.end(), ShowReview); break;              case'3':for_each(new_pri.begin(), new_pri.end(), ShowReview); break;              case'4':for_each(new_rat.begin(), new_rat.end(), ShowReview); break;              case'5':for_each(new_pri.rbegin(), new_pri.rend(), ShowReview);//反向输出break;              case'6':for_each(new_rat.rbegin(), new_rat.rend(), ShowReview);break;              case 'q':break;              default: std::cout << "Error input,please enter the true type:\n";                  break;  }Showmenu();              cin >> key;  }}elsecout<<"books is empty,end!\n";return 0;}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;std::cout<<"Enter book price: ";std::cin>>rr.price;if(!std::cin)return false;while(std::cin.get() != '\n')continue;return true;}bool operator<( const std::shared_ptr<Review> & r1,const std::shared_ptr<Review> & r2){if (r1->title < r2->title)          return true;           else          return false;  }bool showRating(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2) //默认升序{      if (r1->rating < r2->rating)          return true;      else          return false;  }  bool showPrice(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2) {      if (r1->price < r2->price)          return true;      else          return false;  }  void ShowReview(const std::shared_ptr<Review> & rr)  {      std::cout<<rr->title<<"\t"<<rr->rating<<"\t"<<rr->price<<std::endl;}  void Showmenu()  {      std::cout<<"display by different choice:\n"<<"1:ordinary order        "<<"2:Alphabetical order\t"<<"        3:Ascending price\n"<<"4:Ascending rating\t"<<"5:Descending order price\t"<<"6:Descending order rating\n"<<"q:quit\n";}