C++ Primer Plus 第六版 第十六章编程练习答案

    xiaoxiao2024-10-28  99

    //question1

    #include <iostream>

    #include <string>

     

    bool is_circle(const std::string & s);

     

    int main() {

        std::string s;

        std::cout << "Enter a word(q to quit): \n";

        while(std::cin >> s && s != "q")

        {

            if(is_circle(s))

                std::cout << "Yes, it's huiwen.\n";

            else

                std::cout << "No, it's not.Try again.\n";

            std::cout << "Enter a word(q to quit): \n";

        }

        return 0;

    }

     

    bool is_circle(const std::string & s)

    {

        std::string s_temp(s);

        reverse(s_temp.begin(), s_temp.end());

        if(s != s_temp)

            return false;

        else

            return true;

    }

    //question2

    #include <iostream> #include <algorithm> #include <cctype> #include <string>

    bool is_circle(std::string & s);

    int main() {

        std::string s;     std::cout << "Enter a word(q to quit): \n";     while(getline(std::cin, s) && s != "q")     {         if(is_circle(s))             std::cout << "Yes, it's huiwen.\n";         else             std::cout << "No, it's not.Try again.\n";         std::cout << "Enter a word(q to quit): \n";     }     return 0; }

    bool is_circle(std::string & s) {     std::string::iterator pd;     for(pd = s.begin(); pd != s.end(); )     {         if(!isalpha(*pd) || isspace(*pd))               s.erase(pd);    //查了半天才发现erase返回下一个迭代器,所以不能在for循环中统一进行pd++,否则会跳过一些字符          else             {              *pd = tolower(*pd);              pd++;         }     }     std::string s_temp(s);     std::cout << s << std::endl;     reverse(s_temp.begin(), s_temp.end());     if(s != s_temp)         return false;     else     return true; }

    //question3

    #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <ctime> #include <vector> #include <cctype>

    using std::string;

    int main() {     using std::cout;     using std::cin;     using std::tolower;     using std::endl;     std::srand(std::time(0));     char play;          std::ifstream ifs;     ifs.open("wordlist.txt", std::ifstream::in);     std::string word;     std::vector<string> wordlist;     if(ifs.good())     {         while(ifs >> word)             wordlist.push_back(word);     }     int length = wordlist.size();     cout << "Will you play a word game? <y/n>";     cin >> play;     play = tolower(play);     while(play == 'y')     {         string target = wordlist[std::rand() % wordlist.size()];         int length = target.length();         string attempt(length, '-');         string badchars;         int guesses = 6;         cout << "Guess my secret word. It has " << length              << " letters, 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";         else             cout << "Sorry, the word is " << target << ".\n";         cout << "Will you play another? <y/n>";         cin >> play;         play = tolower(play);       }          cout << "Bye\n";     ifs.close();     return 0; } 

    //question4

    #include <iostream> #include <algorithm> #include <set> #include <iterator> //#include <string>

    int reduce(long ar[], int n); int main() {     long ar1[5] = {45000, 3400, 45000, 100000, 2500};     int resize = reduce(ar1, 5);     std::cout << "array1: \n";     for (int i = 0; i < resize; i++)     {         std::cout << ar1[i] << " ";      }     return 0; }

    int reduce(long ar[], int n) {     std::set<long> arrayset;     int i;     for (i = 0; i < n; i++)         arrayset.insert(arrayset.end(), ar[i]);     auto pd = arrayset.begin();     for (i = 0; i < arrayset.size(); i++, pd++)         ar[i] = *pd;     return arrayset.size(); }

    //question5

    #include <iostream> #include <algorithm> #include <set> #include <iterator> #include <string>

    template <typename T> int reduce(T ar[], int n) {     std::set<T> arrayset;     int i;     for (i = 0; i < n; i++)         arrayset.insert(arrayset.end(), ar[i]);     auto pd = arrayset.begin();     for (i = 0; i < arrayset.size(); i++, pd++)         ar[i] = *pd;     return arrayset.size(); }

    int main() {     long ar1[5] = {45000, 3400, 45000, 100000, 2500};     int resize = reduce(ar1, sizeof(ar1)/sizeof(long));     std::cout << "array1: \n";     int i;     for (i = 0; i < resize; i++)     {         std::cout << ar1[i] << " ";      }          std::string ar2[6] = {"it", "aboard", "it", "zone", "quit", "aa"};     resize = reduce(ar2, sizeof(ar2)/sizeof(std::string));     std::cout << "\narray2: \n";     for (i = 0; i < resize; i++)     {         std::cout << ar2[i] << " ";      }     return 0; }

    //question6

    //16_6.cpp #include "customer.h" #include <iostream> #include <queue> #include <cstdlib> #include <ctime> const int MIN_PER_HR = 60;

    bool newcustomer(double x);

    int main() {     using std::cin;     using std::cout;     using std::endl;     using std::ios_base;     std::srand(std::time(0));          cout << "Case Study: Bank of Heather Automatic Teller\n";     cout << "Enter maximum size of queue: ";     int qs;     cin >> qs;     std::queue<Item> line;          cout << "Enter the average number of customers per hour: ";     int hours;     cin >> hours;          long cyclelimit = MIN_PER_HR *hours;          cout << "Enter the average number of customers per hour: ";     double perhour;     cin >> perhour;     double min_per_cust;     min_per_cust = MIN_PER_HR / perhour;          Item temp;     long turnaways = 0;     long customers = 0;     long served = 0;     long sum_line = 0;     int wait_time = 0;     long line_wait = 0;          for (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())         {             temp = line.front();             wait_time = temp.ptime();             line.pop();             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";     }     else         cout << "No customers!\n";     cout << "Done!\n";     return 0; }

    bool newcustomer(double x) {     return (std::rand() * x / RAND_MAX < 1); }

    //customer.h #ifndef CUSTOMER_H #define CUSTOMER_H #include <cstdlib>

    class Customer {     private:         long arrive;         int processtime;     public:         Customer() {arrive = processtime = 0;}         void set(long when);         long when() const {return arrive;}         int ptime() const {return processtime;} };

    void Customer::set(long when) {     processtime = std::rand() % 3 + 1;     arrive = when; } typedef Customer Item; #endif

    //question7

    #include <iostream> #include <vector> #include <algorithm>

    std::vector<int> Lotto(int a, int b);

    int main() {     std::vector<int> winners;     winners = Lotto(51,6);     std::vector<int>::iterator pd;     std::cout << "winners: \n";     for (pd = winners.begin(); pd != winners.end(); pd++)         std::cout << *pd << " ";     return 0; }

    std::vector<int> Lotto(int a, int b) {     std::vector<int> list, win;     for(int i = 0; i < b; i++)     {         for(int j = 0; j < a; j++)             list.push_back(j+1);         std::random_shuffle(list.begin(), list.end());         win.push_back(*list.begin());     }     return win; }

     

    //question8

    #include <iostream> #include <set> #include <string> #include <algorithm> int main() { std::cout << "Enter Mat's friends(q to quit): \n"; std::string name; std::set<std::string> namelist_Mat, namelist_Pat, common; std::set<std::string>::iterator pd; while(std::cin >> name && name != "q") namelist_Mat.insert(name); std::cout << "\nMat's friends are: \n"; for(pd = namelist_Mat.begin(); pd != namelist_Mat.end(); pd++) std::cout << *pd << " "; std::cout << "\nEnter Pat's friends(q to quit): \n"; while(std::cin >> name && name != "q") namelist_Pat.insert(name); std::cout << "\nPat's friends are: \n"; for(pd = namelist_Pat.begin(); pd != namelist_Pat.end(); pd++) std::cout << *pd << " "; std::set_union(namelist_Mat.begin(),namelist_Mat.end(),namelist_Pat.begin(), namelist_Pat.end(), inserter(common, common.begin())); std::cout << "\nInvited friends are: \n"; for(pd = common.begin(); pd != common.end(); pd++) std::cout << *pd << " "; return 0; }

     

    //question9

    #include <iostream> #include <ctime> #include <vector> #include <list> #include <stdlib.h> #include <algorithm>

    int main() {     srand (time(NULL));     std::vector<int> vi0;     for(int i = 0; i < 1000000; i++)         vi0.push_back(rand());     std::vector<int> vi(vi0);     std::list<int> li(vi0.begin(), vi0.end());     clock_t start = clock();     std::sort(vi.begin(), vi.end());     clock_t end = clock();     std::cout << "Sort the vector: ";     std::cout << (double)(end - start) / CLOCKS_PER_SEC << "\n";          start = clock();     li.sort();//忘了stl中sort不能直接用于list,只能用list自带的sort函数      end = clock();     std::cout << "Sort the list: ";     std::cout << (double)(end - start) / CLOCKS_PER_SEC << "\n";          li.assign(vi0.begin(), vi0.end());     start = clock();     vi.assign(li.begin(), li.end());     std::sort(vi.begin(), vi.end());     li.assign(vi.begin(), vi.end());     end = clock();     std::cout << "Time: ";     std::cout << (double)(end - start) / CLOCKS_PER_SEC << "\n";     return 0; }

    //question10

    #include <iostream> #include <string> #include <vector> #include <algorithm> #include <memory> //shared_ptr

    struct Review {     std::string title;     int rating;     int price; }; 

    bool operator<(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2); bool ratingup_com(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2); bool ratingdown_com(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2); bool priceup_com(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2); bool pricedown_com(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2); bool FillReview(Review & rr); void ShowReview(const std::shared_ptr<Review> & p);

    int main() {     using namespace std;          vector<shared_ptr<Review> > books;     Review temp;     while(FillReview(temp))     {         shared_ptr<Review> pd (new Review(temp));         books.push_back(pd);      }     if (books.size() > 0)     {         cout << "Please choose the way to sort: "              << "n: normal, a: alpha, r: rating(up), s: rating(down), p: price(up), d: price(down), q: quit\n";         char a;         while(cin >> a && a != 'q')         {             switch(a)             { //                case "n":  sort(books.begin(), books.end());  //                           break; //                case "a":  sort(books.begin(), books.end());  //                           break;                 case 'r': sort(books.begin(), books.end(), ratingup_com);                             break;                 case 's': sort(books.begin(), books.end(), ratingdown_com);                             break;                 case 'p': sort(books.begin(), books.end(), priceup_com);                             break;                 case 'd': sort(books.begin(), books.end(), pricedown_com);                             break;                 default:   sort(books.begin(), books.end());                             break;             }              for_each(books.begin(), books.end(), ShowReview);              cout << "Please choose the way to sort: "                   << "n: normal, a: alpha, r: rating(up), s: rating(down), p: price(up), d: price(down), q: quit\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;     std::cout << "Enter book price: ";     std::cin >> rr.price;     if (!std::cin)         return false;     while (std::cin.get()!='\n')         continue;     return true; }

    void ShowReview(const std::shared_ptr<Review> & p) {     std::cout << p->rating << "\t" << p->title << "\t" << p->price << std::endl; }

    bool operator<(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2) {     if (p1->title < p2->title)         return true;     else if (p1->title == p2->title && p1->rating < p2->rating)         return true;     else         return false; }

    bool ratingup_com(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2) {     if (p1->rating < p2->rating)         return true;     else         return false; }

    bool ratingdown_com(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2) {     if (p1->rating > p2->rating)         return true;     else         return false; }

    bool priceup_com(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2) {     if (p1->price < p2->price)         return true;     else         return false; }

    bool pricedown_com(const std::shared_ptr<Review> & p1, const std::shared_ptr<Review> & p2) {     if (p1->price > p2->price)         return true;     else         return false; }

    最新回复(0)