C++ Primer Plus 第十六章 (16章) 编程题答案

16.10.1

  1. // 16.10.1.cpp: 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <string>
  5. #include <iostream>
  6. using namespace std;
  7. bool reversed_same(string & st);
  8. int main()
  9. {
  10.     string str;
  11.     cout << "Enter a sentence or words.\n"
  12.         <<"type \"quit\" to quit\n";
  13.     getline(cin, str);
  14.     while (str != "quit")
  15.     {
  16.         if (reversed_same(str))
  17.             cout << "It's the same after reversing.\n";
  18.         else cout << "It's not the same after reversing.\n";
  19.         getline(cin, str);
  20.     }
  21.     return 0;
  22. }
  23. bool reversed_same(string & st)
  24. {
  25.     string temp = st;
  26.     reverse(temp.begin(), temp.end());
  27.     if (temp == st)
  28.         return true;
  29.     else return false;    
  30. }

16.10.2

  1. // 16.10.2.cpp: 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <string>
  5. #include <iostream>
  6. #include <cctype>
  7. using namespace std;
  8. bool reversed_same(string & st);
  9. int main()
  10. {
  11.     string str;
  12.     cout << "Enter a sentence or words.\n"
  13.         << "type \"quit\" to quit\n";
  14.     getline(cin, str);
  15.     while (str != "quit")
  16.     {
  17.         if (reversed_same(str))
  18.             cout << "It's the same after reversing.\n";
  19.         else cout << "It's not the same after reversing.\n";
  20.         getline(cin, str);
  21.     }
  22.     return 0;
  23. }
  24. bool reversed_same(string & st)
  25. {
  26.     string only_alpha;
  27.     int limit = st.size();
  28.     for (int i = 0; i < limit; i++)
  29.         if (isalpha(st[i]))
  30.             only_alpha += tolower(st[i]);
  31.     string temp = only_alpha;
  32.     reverse(temp.begin(), temp.end());
  33.     if (temp == only_alpha)
  34.         return true;
  35.     else return false;
  36. }

 16.10.3

  1. // 16.10.3.cpp: 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include <fstream>
  6. #include <vector>
  7. #include <string>
  8. #include <algorithm>
  9. using namespace std;
  10. void Show(string & s) { cout << s; }
  11.  
  12. int main()
  13. {
  14.     ifstream fin;
  15.     fin.open("16103words.txt");
  16.     if (fin.is_open() == false)
  17.     {
  18.         cerr << "Can't open file. Bye \n";
  19.         exit(EXIT_FAILURE);
  20.     }
  21.     vector <string> vec;
  22.     string temp;
  23.     fin >> temp;
  24.     while (fin)
  25.     {
  26.         vec.push_back(temp);
  27.         fin >> temp;
  28.     }
  29.     for_each(vec.begin(), vec.end(), Show);
  30.     fin.close();
  31.     
  32.     return 0;
  33. }
  34.  

16.10.4

  1. // 16.10.4.cpp: 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <list>
  5. #include <algorithm>
  6. #include <cstdlib>
  7. #include <ctime>
  8. #include <iostream>
  9. using namespace std;
  10. int reduce(long ar[], int n);
  11. int main()
  12. {
  13.     srand(time(0));    
  14.     long data[50];
  15.     for (int i =0 ; i <50; i++)
  16.     {
  17.         data[i] = rand() % 20;
  18.     }
  19.     
  20.     cout << "before reducing : 50\n" << "after reducing: ";
  21.     cout << reduce(data, 50);
  22.     return 0;
  23. }
  24. int reduce(long ar[], int n)
  25. {
  26.     list <long> lis;    
  27.     for (int i = 0; i < n; i++)
  28.         lis.push_back(ar[i]);
  29.     lis.sort();
  30.     lis.unique();
  31.     int count = lis.size();    
  32.     return count;
  33. }
  34. //list的成员函数sort(),和unique()更简单好用。
  35. //使用vector 和非成员函数unique()时,unique失效了,不明原因。

16.10.5

  1. // 16.10.5.cpp: 定义控制台应用程序的入口点。
  2.  
  3. #include "stdafx.h"
  4. #include <list>
  5. #include <algorithm>
  6. #include <cstdlib>
  7. #include <ctime>
  8. #include <iostream>
  9. using namespace std;
  10. template <class T>
  11. int reduce(T ar[], int n);
  12. int main()
  13. {
  14.     srand(time(0));
  15.     long data[50];
  16.     for (int i = 0; i <50; i++)
  17.     {
  18.         data[i] = rand() % 20;
  19.     }
  20.     cout << "before reducing : 50\n" << "after reducing: ";
  21.     cout << reduce(data, 50);
  22.     return 0;
  23. }
  24. template <class T>
  25. int reduce(T ar[], int n)
  26. {
  27.     list <T> lis;
  28.     for (int i = 0; i < n; i++)
  29.         lis.push_back(ar[i]);
  30.     lis.sort();
  31.     lis.unique();
  32.     int count = lis.size();
  33.     return count;
  34. }
  35.  

16.10.6

  1. //标头.h  
  2. #pragma once
  3. #ifndef QUEUE_H_
  4. #define QUEUE_H_
  5. #include <cstdlib>
  6. #include <ctime>
  7. using namespace std;
  8. // This queue will contain Customer items
  9. class Customer
  10. {
  11. private:
  12.     long arrive;        // arrival time for customer
  13.     int processtime;    // processing time for customer
  14. public:
  15.     Customer() : arrive(0), processtime(0) {}
  16.     void set(long when);
  17.     long when() const { return arrive; }
  18.     int ptime() const { return processtime; }
  19. };
  20. void Customer::set(long when)
  21. {
  22.     processtime = rand() % 3 + 1;
  23.     arrive = when;
  24. }
  25.  
  26. typedef Customer Item;
  27. #endif
  1. // 16.10.6.cpp: 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include "标头.h"
  5. #include <iostream>
  6. #include <cstdlib>
  7. #include <ctime>
  8. #include <queue>
  9. using namespace std;
  10. const int MIN_PER_HR = 60;
  11. bool newcustomer(double x); // is there a new customer?
  12. int main()
  13. {    
  14.     srand(time(0));    //  random initializing of rand()
  15.     cout << "Case Study: Bank of Heather Automatic Teller\n";
  16.     cout << "Enter maximum size of queue: ";
  17.     int qs;
  18.     cin >> qs;
  19.     queue <Item> line;         // line queue holds up to qs people
  20.     cout << "Enter the number of simulation hours: ";
  21.     int hours;              //  hours of simulation
  22.     cin >> hours;
  23.     // simulation will run 1 cycle per minute
  24.     long cyclelimit = MIN_PER_HR * hours; // # of cycles
  25.     cout << "Enter the average number of customers per hour: ";
  26.     double perhour;         //  average # of arrival per hour
  27.     cin >> perhour;
  28.     double min_per_cust;    //  average time between arrivals
  29.     min_per_cust = MIN_PER_HR / perhour;
  30.     Item temp;              //  new customer data
  31.     long turnaways = 0;     //  turned away by full queue
  32.     long customers = 0;     //  joined the queue
  33.     long served = 0;        //  served during the simulation
  34.     long sum_line = 0;      //  cumulative line length
  35.     int wait_time = 0;      //  time until autoteller is free
  36.     long line_wait = 0;     //  cumulative time in line
  37.  
  38.     for (int cycle = 0; cycle < cyclelimit; cycle++)
  39.     {
  40.         if (newcustomer(min_per_cust))  // have newcomer
  41.         {
  42.             if (line.size() == qs)
  43.                 turnaways++;
  44.             else
  45.             {
  46.                 customers++;
  47.                 temp.set(cycle);    // cycle = time of arrival
  48.                 line.push(temp); // add newcomer to line
  49.             }
  50.         }
  51.         if (wait_time <= 0 && !line.empty())
  52.         {
  53.             ;
  54.             line.pop();      // attend next customer
  55.             wait_time = temp.ptime(); // for wait_time minutes
  56.             line_wait += cycle - temp.when();
  57.             served++;
  58.         }
  59.         if (wait_time > 0)
  60.             wait_time--;
  61.         sum_line += line.size();
  62.     }
  63.     if (customers > 0)
  64.     {
  65.         cout << "customers accepted: " << customers << endl;
  66.         cout << "  customers served: " << served << endl;
  67.         cout << "         turnaways: " << turnaways << endl;
  68.         cout << "average queue size: ";
  69.         cout.precision(2);
  70.         cout.setf(ios_base::fixed, ios_base::floatfield);
  71.         cout << (double)sum_line / cyclelimit << endl;
  72.         cout << " average wait time: "
  73.             << (double)line_wait / served << " minutes\n";
  74.     }
  75.     else
  76.         cout << "No customers!\n";
  77.     cout << "Done!\n";
  78.     // cin.get();
  79.     // cin.get();
  80.     return 0;
  81. }
  82. bool newcustomer(double x)
  83. {
  84.     return (rand() * x / RAND_MAX < 1);
  85. }

 16.10.7

  1. // 16.10.7.cpp: 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <vector>
  5. #include <algorithm>
  6. #include <iostream>
  7. using namespace std;
  8. using namespace std;
  9. vector<int> lotto(int maxnum, int picked);
  10. void show(int n) { cout << n << "\t"; }
  11. int main()
  12. {
  13.     vector <int >winners;
  14.     winners = lotto(51, 6);
  15.     for_each(winners.begin(), winners.end(), show);
  16.     //for_each最后的show函数,只要函数名。不能加括号
  17.     return 0;
  18. }
  19. vector<int> lotto(int maxnum, int picked)
  20. {
  21.     vector<int> temp;
  22.     int val;
  23.     vector <int> result;
  24.     
  25.     for (int i = 0; i < maxnum; i++)
  26.     {
  27.         val = i + 1;
  28.         temp.push_back(val);
  29.     }
  30.     for (int i = 0; i < picked; i++)
  31.     {
  32.         random_shuffle(temp.begin(), temp.end());
  33.         result.push_back(*temp.begin());
  34.     }
  35.     return result;
  36. }

16.10.8

  1. // 16.10.8.cpp: 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <string>
  5. #include <set>
  6. #include <algorithm>
  7. #include <iostream>
  8. #include <iterator>
  9. using namespace std;
  10. void show(string s) { cout << s << endl; }
  11. int main()
  12. {
  13.     set<string> Mat_set;
  14.     set<string> Pat_set;
  15.     string temp;
  16.     cout << "Mat's turn to type,\"quit\" to quit\n";
  17.     getline(cin, temp);
  18.     while (temp != "quit")
  19.     {
  20.         Mat_set.insert(temp);
  21.         getline(cin, temp);
  22.     }
  23.     cout << "Pat's turn to type,\"quit\" to quit\n";
  24.     getline(cin, temp);
  25.     while (temp != "quit")
  26.     {
  27.         Pat_set.insert(temp);
  28.         getline(cin, temp);
  29.     }
  30.     cout << "Number of Mat's friends\t" << Mat_set.size() << endl;
  31.     cout << "Number of Pat's friends\t" << Pat_set.size() << endl;
  32.     set<string> Merged;
  33.     Merged.insert(Mat_set.begin(), Mat_set.end());
  34.     Merged.insert(Pat_set.begin(), Pat_set.end());
  35.     cout << "Number of Merged list.\t" << Merged.size() << endl;
  36.     for_each(Merged.begin(), Merged.end(), show);    
  37.     return 0;
  38. }

16.10.9

  1. // 16.10.9.cpp: 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <cstdlib>
  5. #include <ctime>
  6. #include <vector>
  7. #include <list>
  8. #include <algorithm>
  9. #include <iostream>
  10. using namespace std;
  11. int main()
  12. {
  13.     srand(time(0));
  14.     long limit = 1000000;
  15.     vector <int> vi0;
  16.     for (int i = 0; i < limit; i++)
  17.         vi0.push_back(rand() % 1000);
  18.     vector <int> vi(vi0.size(),1);
  19.     list <int> li(vi0.size(),1);
  20.     
  21.     clock_t start = clock();
  22.     sort(vi.begin(), vi.end());
  23.     clock_t end = clock();
  24.     cout << "for vector   " << (double)(end - start) / CLOCKS_PER_SEC << endl;
  25.     start = clock();
  26.     li.sort();
  27.     end = clock();
  28.     cout << "for list   " << (double)(end - start) / CLOCKS_PER_SEC << endl;
  29.     //experiment 2
  30.     cout << "experiment 2:\n";
  31.     copy(vi0.begin(), vi0.end(), li.begin());
  32.  
  33.     start = clock();
  34.     copy(li.begin(), li.end(), vi.begin());
  35.     sort(vi.begin(), vi.end());
  36.     copy(vi.begin(), vi.begin(), li.begin());
  37.     end = clock();
  38.     cout <<  (double)(end - start) / CLOCKS_PER_SEC << endl;
  39.  
  40.     return 0;
  41. }
  42.  

16.10.10

// 16.10.10.cpp: 定义控制台应用程序的入口点。

  1. //
  2. #include "stdafx.h"
  3. #include <iostream>
  4. #include <string>
  5. #include <vector>
  6. #include <algorithm>
  7. using namespace std;
  8. struct Review {
  9.     std::string title;
  10.     int rating;
  11.     double price;
  12. };
  13. bool operator<(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
  14. bool worseThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
  15. bool FillReview(Review & rr);
  16. void ShowReview(const shared_ptr<Review> & rr);
  17. void showmenu();
  18. bool sorting1(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
  19. int main()
  20. {
  21.     using namespace std;
  22.     vector <shared_ptr<Review>> books;
  23.  
  24.     Review temp;
  25.     while (FillReview(temp)) {
  26.         shared_ptr<Review> pd_temp(new Review(temp));
  27.         books.push_back(pd_temp);
  28.     }
  29.     if (books.size() > 0)
  30.     {
  31.         cout<< "choose a way to show data.";
  32.         int choice;
  33.         showmenu();
  34.         cin >> choice;
  35.         while (choice!=7)
  36.         {
  37.             switch (choice)
  38.             {
  39.             case 1:
  40.                 for_each(books.begin(), books.end(), ShowReview);
  41.                 break;
  42.             case 2:
  43.                 sort(books.begin(), books.end());
  44.                 for_each(books.begin(), books.end(), ShowReview);
  45.                 break;
  46.             case 3:
  47.                 sort(books.begin(), books.end(), worseThan);
  48.                 for_each(books.begin(), books.end(), ShowReview);
  49.                 break;
  50.             case 4:
  51.                 sort(books.begin(), books.end(), worseThan);
  52.                 reverse(books.begin(), books.end());
  53.                 for_each(books.begin(), books.end(), ShowReview);
  54.                 break;
  55.             case 5:
  56.                 sort(books.begin(), books.end(), sorting1);
  57.                 for_each(books.begin(), books.end(), ShowReview);
  58.                 break;
  59.             case 6:
  60.                 sort(books.begin(), books.end(), sorting1);
  61.                 reverse(books.begin(), books.end());
  62.                 for_each(books.begin(), books.end(), ShowReview);
  63.                 break;
  64.             default:
  65.                 cout << "wrong number.";
  66.                 continue;
  67.             }
  68.             showmenu();
  69.             cin >> choice;
  70.         }
  71.     }
  72.     else
  73.         cout << "No entries. ";
  74.     cout << "Bye.\n";
  75.     // cin.get();
  76.     return 0;
  77. }
  78. bool operator<(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
  79. {
  80.     if (r1->title < r2->title)
  81.         return true;
  82.     else if (r1->title == r2->title && r1->rating < r2->rating)
  83.         return true;
  84.     else
  85.         return false;
  86. }
  87.  
  88. bool worseThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
  89. {
  90.     if (r1->rating < r2->rating)
  91.         return true;
  92.     else
  93.         return false;
  94. }
  95. bool sorting1(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2)
  96. {
  97.     if (r1->price < r2->price)
  98.         return true;
  99.     if (r1->price == r2->price && r1->rating < r2->rating)
  100.         return true;
  101.     else
  102.         return false;
  103. }
  104.  
  105. bool FillReview(Review & rr)
  106. {
  107.     std::cout << "Enter book title (quit to quit): ";
  108.     getline(cin, rr.title);
  109.     if (rr.title == "quit")
  110.         return false;
  111.     cout << "Enter book price:  ";
  112.     cin >> rr.price;
  113.     if (!cin)
  114.         return false;
  115.     
  116.     std::cout << "Enter book rating: ";
  117.     std::cin >> rr.rating;
  118.     if (!cin)
  119.         return false;
  120.     // get rid of rest of input line
  121.     while (std::cin.get() != '\n')
  122.         continue;
  123.     return true;
  124. }
  125. void ShowReview(const shared_ptr<Review> & rr)
  126. {
  127.     cout << "name\trating\tprice\n";
  128.     cout << rr->title << "\t" << rr->rating << "\t" << rr->price << endl;
  129. }
  130. void showmenu()
  131. {
  132.     cout << "Please enter 1,2,3,4,5,6 or 7\n"
  133.         << "1) by original order \t 2) by alphabet order  \n"
  134.         << "3) by rating up      \t 4) by rating down     \n"
  135.         << "5) by pricing up     \t 6) by pricing down    \n"  
  136.         << "7) quit  \n";
  137. }

猜你喜欢

转载自blog.csdn.net/shengda_mao1118/article/details/81674229
今日推荐