神秘博客

C++ Primer Plus [第六版]第16章编程练习题答案

1

#include <iostream>
#include <string>

bool Palindrome(const std::string &st);

int main()
{
  using namespace std;
  string s1;
  string s2;

  cout << "输入内容[\"quit\"退出]:\n";
  while (getline(cin, s1) && s1 != "quit")
  {
    cout << s1;
    if (Palindrome(s1))
      cout << " 是回文.\n";
    else
      cout << " 不是回文.\n";
  }
  cout << "再见\n";

  system("pause");
  return 0;
}

bool Palindrome(const std::string &st)
{
  std::string temp(st.rbegin(), st.rend());

  /*
  //另一个方法是使用copy,不过要先创建等同st大小的temp对象,temp=st;
  copy(st.rbegin(), st.rend(), temp.begin());  //拷贝
  //还可以使用
  temp.insert(temp.begin(), st.rbegin(), st.rend()); //插入
  */


  return st == temp;
}

 

2

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

bool Palindrome(const std::string &st);

int main()
{
  using namespace std;
  string s1;
  string s2;

  cout << "输入内容[\"quit\"退出]:\n";
  while (getline(cin, s1) && s1 != "quit")
  {
    cout << s1;
    if (Palindrome(s1))
      cout << " 是回文.\n";
    else
      cout << " 不是回文.\n";
  }
  cout << "再见\n";

  system("pause");
  return 0;
}

bool Palindrome(const std::string &st)
{
  std::string temp1;

  for (int i = st.size() - 1; i >= 0; i--)
  {
    if (isalnum(st[i]))
      temp1 += tolower(st[i]);
  }
  std::string temp2(temp1.rbegin(), temp1.rend());
  return temp1 == temp2;
}

3

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <fstream>  //文件头文件
#include <vector>

using std::string;
/*
const int NUM = 26;

const string wordlist[NUM] =
{
  "apiary", "beetle", "cereal",
  "danger", "ensign", "florid", "garage", "health", "insult",
  "jackal", "keeper", "loaner", "manage", "nonce", "onset",
  "plaid", "quilt", "remote", "stolid", "train", "useful",
  "valid", "whence", "xenon", "yearn", "zippy"
};
*/
int main()
{
  using namespace std;

  ifstream file;
  file.open("data.txt");  //打开数据文件
  if (!file.is_open())  //如果打开失败退出
  {
    cout << "无法打开数据文件\"data.txt\", 请检查...\n";
    exit(EXIT_FAILURE);
  }
  vector<string> wordlist;
  string temps;
  while (file >> temps)
    wordlist.push_back(temps);
  const int NUM = wordlist.size();
  if (file.eof())
    cout << "读取了 " << NUM << " 个单词, 正常读取数据文件完成...\n";
  else
    cout << "读取了 " << NUM << " 个单词, 未正常读取数据文件...\n";

  srand(unsigned int(time(0)));
  char play;
  cout << "你会玩文字游戏吗?[y/n]\n";
  cin >> play;
  play = tolower(play);
  while (play == 'y')
  {
    string target = wordlist[rand() % NUM]; //随机选取一个单词
    int length = target.length(); //选取单词的长度
    string attempt(length, '-'); //玩家的单词
    string badchars;  //错误选择字母记录
    int guesses = 6; //错误机会
    cout << "猜猜我的秘密单词. 它有 " << length << " 个字母, 你一次猜一个字母.\n你的游戏机会 " << guesses << " 次.\n";
    cout << "你的单词: " << attempt << endl;
    while (guesses > 0 && attempt != target)
    {
      char letter; //临时猜测字母
      cout << "猜一个字母:";
      cin >> letter;
      if (badchars.find(letter) != string::npos || attempt.find(letter) != string::npos)
      {
        cout << "你已经猜到了. 再试一次.\n";
        continue;
      }
      int loc = target.find(letter); //猜测字母处于单词的位置
      if (loc == string::npos)
      {
        cout << "哦, 糟糕的猜测.\n";
        --guesses;
        badchars += letter;
      }
      else
      {
        cout << "很好的猜测.\n";
        attempt[loc] = letter;
        loc = target.find(letter, loc + 1); //检查是否还有同一个字母
        while (loc != string::npos)
        {
          attempt[loc] = letter;
          loc = target.find(letter, loc + 1);
        }
      }
      cout << "你的单词: " << attempt << endl;
      if (attempt != target)
      {
        if (badchars.size() > 0)
          cout << "糟糕的选择: " << badchars << endl;
        cout << "剩下 " << guesses << " 次游戏机会\n";
      }
    }
    if (guesses > 0)
      cout << "那就对了!\n";
    else
      cout << "很抱歉,这个单词是 " << target << ".\n";
    cout << "你会玩文字游戏吗?[y/n]\n";
    cin >> play;
    play = tolower(play);
  }

  cout << "再见\n";

  file.close();  //关闭文件
  system("pause");
  return 0;
}

4

#include <iostream>
#include <list>

int reduce(long ar[], int n);

int main()
{
  using namespace std;
  const int SIZE = 10;
  long num[SIZE];

  cout << "请输入10个数字, 我将返回没有重复的数字个数:\n";
  for (int i = 0; i < SIZE; i++)
    cin >> num[i];
  cout << "不重复的数字共有 " << reduce(num, SIZE) << " 个.\n";

  system("pause");
  return 0;
}

int reduce(long ar[], int n)
{
  std::list<int> temp(ar, ar + n);

  temp.sort();
  temp.unique();

  return temp.size();
}

5

#include <iostream>
#include <list>
#include <string>

template <typename T>
int reduce(T ar[], int n);

int main()
{
  using namespace std;
  const int SIZE = 10;
  long num[SIZE];

  cout << "请输入10个数字, 我将返回没有重复的数字个数:\n";
  for (int i = 0; i < SIZE; i++)
    cin >> num[i];
  cout << "不重复的数字共有 " << reduce(num, SIZE) << " 个.\n";

  string words[SIZE];
  cout << "请输入10个单词, 我将返回没有重复单词的个数:\n";
  for (int i = 0; i < SIZE; i++)
    cin >> words[i];
  cout << "不重复的单词共有 " << reduce(words, SIZE) << " 个.\n";

  system("pause");
  return 0;
}

template <typename T>
int reduce(T ar[], int n)
{
  std::list<T> temp(ar, ar + n);

  temp.sort();
  temp.unique();

  return temp.size();
}

6

#ifndef QUEUE_H_
#define QUEUE_H_
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; }
};
typedef Customer Item;

#endif
#include "Queue.h"
#include <cstdlib>

//保存客户到达时间和生成随机服务时间
void Customer::set(long when)
{
  processtime = std::rand() % 3 + 1;
  arrive = when;
}
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>   // for time()
#include <queue>
#include "Queue.h"
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;

  srand(unsigned int(time(0)));

  cout << "案例研究:希瑟银行自动柜员机\n";
  cout << "输入队列的最大大小: ";
    int qs;
    cin >> qs;
    std::queue<Item> line;         

  cout << "输入模拟小时数: ";
    int hours;              //  模拟小时
    cin >> hours;

    long cyclelimit = MIN_PER_HR * hours; // 模拟分钟

  cout << "输入每小时的平均客户数量: ";
    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;     //  客户到被服务的等待时间

  int cycle; //当前分钟
    for (cycle = 0; cycle < cyclelimit; cycle++)
    {
        if (newcustomer(min_per_cust))  // 是否有客户到来
        {
      if (line.size() == qs)  //判断队列是否已满
                turnaways++;
            else
            {
                customers++;
                temp.set(cycle);    
                line.push(temp); // line 插入新客户
            }
        }
        if (wait_time <= 0 && !line.empty())
        {
      temp = line.front(); //返回队首
      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 << endl;
        cout << "客户服务: " << served << endl;
        cout << "总拒绝人数: " << turnaways << endl;
        cout << "平均队列大小: ";
        cout.precision(2);
        cout.setf(ios_base::fixed, ios_base::floatfield);
        cout << (double) sum_line / cyclelimit << endl;
        cout << "平均等待时间: "
             << (double) line_wait / served << " 分钟\n";
    }
    else
    cout << "没客户!\n";
  cout << "完成\n";

  system("pause");
    return 0;
}

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

7

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

std::vector<int> Lotto(const int &a, const int &b);
void Show(const int &t);

int main()
{
  using namespace std;
  vector<int> winners;
  winners = Lotto(33, 6);
  vector<int> blue;
  blue = Lotto(16, 1);

  cout << "红: ";
  for_each(winners.begin(), winners.end(), Show);
  cout.put('\t');

  cout << "蓝: ";
  for_each(blue.begin(), blue.end(), Show);
  cout.put('\n');

  system("pause");
  return 0;
}

std::vector<int> Lotto(const int &a, const int &b)
{
  std::vector<int> temp;
  std::vector<int> num;

  for (int i = 1; i <= a; i++)
    temp.push_back(i);
  for (int i = 0; i < b; i++)
  {
    random_shuffle(temp.begin(), temp.end());  //随机排序
    num.push_back(*temp.begin());
  }
  std::sort(num.begin(), num.end());

  return num;
}

void Show(const int &t)
{
  std::cout << t << " ";
}

8

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

void Show(const std::string &st);

int main()
{
  using namespace std;

  list<string> MatFriend;
  cout << "请输入 Mat 的朋友[\"quit\"退出]: \n";
  string temp;
  while (getline(cin, temp) && temp != "quit")
    MatFriend.push_back(temp);

  list<string> PatFriend;
  cout << "请输入 Pat 的朋友[\"quit\"退出]: \n";
  while (getline(cin, temp) && temp != "quit")
    PatFriend.push_back(temp);

  cout << "Mat 的朋友: \n";
  for_each(MatFriend.begin(), MatFriend.end(), Show);
  cout.put('\n');

  cout << "Pat 的朋友: \n";
  for_each(PatFriend.begin(), PatFriend.end(), Show);
  cout.put('\n');

  list<string> Friend;
  list<string>::iterator p;
  Friend = MatFriend;
  for (p = PatFriend.begin(); p != PatFriend.end(); p++)
    Friend.push_back(*p);
  Friend.sort(); //排序
  Friend.unique(); //去除相邻重复值

  cout << "Mat and Pat 共同朋友: \n";
  for_each(Friend.begin(), Friend.end(), Show);
  cout.put('\n');

  system("pause");
  return 0;
  

}
void Show(const std::string &st)
{
  std::cout << st << '\n';
}

9

#include <iostream>
#include <vector>
#include <list>
#include <ctime>
#include <algorithm>

int main()
{
  using namespace std;
  srand(unsigned int(time(0)));
  const int SIZE = 10000;
  vector<int> vi0;
  for (int i = 0; i < SIZE; i++)
    vi0.push_back(rand() % 10000 + 1);

  vector<int> vi(vi0);
  list<int> li;
  li.insert(li.end(), vi0.begin(), vi0.end());  //插入

  clock_t start = clock();
  sort(vi.begin(), vi.end());
  clock_t end = clock();
  cout << "vi 排序使用时间: " << (double)(end = start) / CLOCKS_PER_SEC << endl;

  start = clock();
  li.sort();
  end = clock();
  cout << "li 排序使用时间: " << (double)(end = start) / CLOCKS_PER_SEC << endl;

  copy(vi0.begin(), vi0.end(), li.begin()); //重置li内容为vi0未排序
  start = clock();
  copy(li.begin(), li.end(), vi.begin());
  sort(vi.begin(), vi.end());
  copy(vi.begin(), vi.end(), li.begin());
  end = clock();
  cout << "li 复制到 vi 中, 对 vi 排序, vi 复制回 li 的使用时间: " << (double)(end = start) / CLOCKS_PER_SEC << endl;

  system("pause");
  return 0;
}

10

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

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

bool operator<(const std::shared_ptr<Review> &r1, const std::shared_ptr<Review> &r2);
bool worseThan(const std::shared_ptr<Review> &r1, const std::shared_ptr<Review> &r2);
bool Price(const std::shared_ptr<Review> &r1, const std::shared_ptr<Review> &r2);
bool FillReview(std::shared_ptr<Review> &rr);
void ShowReview(const std::shared_ptr<Review> &rr);
void menu();

int main()
{
  using namespace std;

  vector<shared_ptr<Review>> books;
  shared_ptr<Review> temp;
  while (FillReview(temp))
    books.push_back(temp);
  vector<shared_ptr<Review>> temps(books);  //拷贝原始数据用于排序不打乱原始数据

  char option;
  menu();
  cout << "\n请输入选项: ";
  while (cin >> option && option != 'q')
  {
    if (books.size() > 0)
    {
      switch (option)
      {
      case '1':
        cout << "谢谢. 您输入了以下 " << books.size() << " 个书籍:\n" << "价格\t评分\t书名\n";
        for_each(books.begin(), books.end(), ShowReview);
        break;
      case '2':
        cout << "谢谢. 您输入了以下 " << temps.size() << " 个书籍:\n";
        sort(temps.begin(), temps.end()); //排序
        cout << "价格\t评分\t书名\n";
        for_each(temps.begin(), temps.end(), ShowReview);
        break;
      case '3':
        cout << "谢谢. 您输入了以下 " << temps.size() << " 个书籍:\n" ;
        sort(temps.begin(), temps.end(), worseThan);
        cout << "价格\t评分\t书名\n";
        for_each(temps.begin(), temps.end(), ShowReview);
        break;
      case '4':
        cout << "谢谢. 您输入了以下 " << books.size() << " 个书籍:\n";
        sort(temps.rbegin(), temps.rend(), worseThan);
        cout << "价格\t评分\t书名\n";
        for_each(temps.begin(), temps.end(), ShowReview);
        break;
      case '5':
        cout << "谢谢. 您输入了以下 " << temps.size() << " 个书籍:\n";
        sort(temps.begin(), temps.end(), Price);
        cout << "价格\t评分\t书名\n";
        for_each(temps.begin(), temps.end(), ShowReview);
        break;
      case '6':
        cout << "谢谢. 您输入了以下 " << temps.size() << " 个书籍:\n";
        sort(temps.rbegin(), temps.rend(), Price);
        cout << "价格\t评分\t书名\n";
        for_each(temps.begin(), temps.end(), ShowReview);
        break;
      default:
        cout << "输入错误, 请输入 1 - 6 or q: \n";
        break;
      }
    }
    else
      cout << "没有条目.\n";
    while (cin.get() != '\n')
      continue;
    menu();
    cout << "\n请输入选项: ";
  }
  

  cout << "再见\n";
  system("pause");
  return 0;
}

void menu()
{
  using std::cout;
  using std::endl;

  cout << "**********书籍显示管理**********\n";
  cout << "1. 按原始顺序显示 \t2. 按字母表顺序显示\n";
  cout << "3. 按评级升序显示 \t4. 按评级降序显示\n";
  cout << "5. 按价格升序显示 \t6. 按价格降序显示\n";
  cout << "q. 退出\n";
  cout << "********************************";
}

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

bool Price(const std::shared_ptr<Review> &r1, const std::shared_ptr<Review> &r2)
{
  if (r1->price < r2->price)
    return true;
  else
    return false;
}

bool worseThan(const std::shared_ptr<Review> &r1, const std::shared_ptr<Review> &r2)
{
  if (r1->rating < r2->rating)
    return true;
  else
    return false;
}

bool FillReview(std::shared_ptr<Review> &rr)
{
  rr = std::shared_ptr<Review>(new Review);
  std::cout << "输入书籍名称[\"quit\"退出]: ";
  getline(std::cin, rr->title);
  if (rr->title == "quit")
    return false;
  std::cout << "输入书籍评分: ";
  std::cin >> rr->rating;
  std::cout << "输入书籍价格: ";
  std::cin >> rr->price;
  if (!std::cin)
    return false;
  while (std::cin.get() != '\n')
    continue;
  return true;
}

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

 

 

版权说明:
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

觉得文章有用就请我吃包辣条吧

微信扫一扫打赏