C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

本章所有编程练习的工程源码可在此处下载(点击此链接下载),供大家参考交流!

 

1. 对于下面的类声明:

class Cow {

         char name[20];

         char *hobby;

         double weight;

public:

         Cow();

         Cow(const char * nm, const char * ho, double wt);

         Cow(const Cow c&);

         ~Cow();

         Cow & operator=(const Cow & c);

         void ShowCow() const;      // display all new data

};

给这个类提供实现,并编写一个使用所有成员函数的小程序。

对于本题,首先题中已经给出了类声明,所以头文件不需要自己定义,可以直接使。

所以头文件cow.h代码如下:

// cow.h -- head file
#ifndef COW_H_
#define COW_H_

class Cow
{
private:
    char name[20];
    char * hobby;
    double weight;
public:
    Cow();
    Cow(const char * nm, const char * ho, double wt);
    Cow(const Cow & c);
    ~Cow();
    Cow & operator=(const Cow & c);
    void ShowCow() const;
};

#endif

在这里,我们之所以在书中提供的类声明的前后加上#ifndef, #define, #endif主要是为了防止该.h文件被重复引用。详情请点击本链接查看

声明了头文件之后,我们首先要考虑去定义头文件中的函数声明。

头文件的私有成员变量中有字符串数组和字符串指针,因此需要用到strcpy_s函数,所以头文件中需要包含<cstring>;在构造函数中,唯一需要注意的就是字符串指针变量需要使用new来动态分配内存,然后再使用strcpy_s函数进行赋值,而相应的析构函数一定要记得将构造函数中使用new动态分配的内存delete掉。

另外,在重载运算符=时,需要在一开始delete一下,以防止此时this指针的hobby变量储存的地址是被分配使用过的。

所以实现文件cow.cpp代码如下:

// cow.cpp -- containing the functions' definition 

#include "stdafx.h"
#include <iostream>
#include <cstring>
#include "cow.h"

using std::cout;
using std::endl;

Cow::Cow()
{
    strcpy_s(name, 20, "new cow");
    hobby = new char[4];
    strcpy_s(hobby, 4, "cow");
    weight = 0.0;
}

Cow::Cow(const char * nm, const char * ho, double wt)
{
    weight = wt;
    hobby = new char[strlen(ho) + 1];
    strcpy_s(hobby, strlen(ho)+1, ho);
    strcpy_s(name, 20, nm);
}

Cow::Cow(const Cow & c)
{
    strcpy_s(name, 20, c.name);
    hobby = new char[strlen(c.hobby) + 1];
    strcpy_s(hobby, strlen(c.hobby) + 1, c.hobby);
    weight = c.weight;
}

Cow::~Cow()
{
    delete[] hobby;
}

Cow & Cow::operator=(const Cow & c)
{
    delete[] hobby;
    hobby = new char[strlen(c.hobby) + 1];
    strcpy_s(hobby, strlen(c.hobby) + 1, c.hobby);
    weight = c.weight;
    strcpy_s(name, 20, c.name);
    return *this;
}

void Cow::ShowCow() const
{
    cout << "Now a new cow!\n";
    cout << "The name is " << name << endl;
    cout << "The hobby is " << hobby << endl;
    cout << "The weight is " << weight << endl;
}

接下来我们来考虑如何使用这些成员函数组成检验文件。

其实本题的文件的主要功能只有3个,各种方式的函数初始化,使用重载的运算符=,使用ShowCow函数进行显示。

检验文件checkcow.cpp代码如下:

// checkcow.cpp -- check all the functions
#include "stdafx.h"
#include <iostream>
#include "cow.h"

using namespace std;

int main()
{
    cout << "Let's start to see our cows!\n";
    Cow c1;
    c1.ShowCow();
    Cow c2("yellow", "eat grass", 123.456);
    c2.ShowCow();
    Cow c3("black", "drink water", 222.333);
    c3.ShowCow();
    c3 = c1;
    Cow c4(c2);
    c3.ShowCow();
    c4.ShowCow();
    system("pause");
    return 0;
}

运行结果如下图所示:

C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

 

2. 通过完成下面的工作来改进String类声明(即将String1.h升级为String2.h)。

a. 对+运算符进行重载,使之可将两个字符串合并成1个。

b. 提供一个Stringlow()成员函数,将字符串中所有的字母字符转换为小写(别忘了cctype系列字符函数)。

c. 提供String()成员函数,将字符串中所有字母字符转换成大写。

d. 提供一个这样的成员函数,它接受一个char参数,返回该字符在字符串中出现的次数。

使用下面的程序来测试您的工作:

(……代码忽略……)

输出应与下面相似:

(……代码忽略……)

本题是在String1.h的基础上进行升级,添加几项功能再测试。

首先,需要重载+运算符,将两个字符串合并成1个,这里看起来只需要添加一个成员函数,其实不然。由于检验文件中既有将string对象相加,又有将字符串指针相加,还存在将string对象和字符串指针相加的情况,所以我们需要对应的定义3个函数来分别重载这三种情况下的+运算符。

其次,提供两个函数将字符串中的所有字母字符转换为小写或大写,这个功能使用<cctype>中的函数将非常轻松。

最后,提供一个成员函数,接受一个char参数,返回该参数在字符串中出现的次数,该函数将需要遍历整个字符串进行计数。

对于头文件,我们只需要添加以上6个函数即可,所以头文件string2.h代码如下:

// string2.h -- fixed and augmented string class definition
#ifndef STRING2_H_
#define STRING2_H_

#include <iostream>
using std::ostream;
using std::istream;

class String
{
private:
    char * str;
    int len;
    static int num_strings;
    static const int CINLIM = 80;
public:
    String(const char * s);
    String();
    String(const String &);
    ~String();
    int length() const { return len; }
    void stringlow();
    void stringup();
    int has(char x);
    String & operator=(const String &);
    String & operator=(const char *);
    char & operator[] (int i);
    const char & operator[] (int i) const;
    friend bool operator<(const String &st1, const String &st2);
    friend bool operator>(const String &st1, const String &st2);
    friend bool operator==(const String &st, const String &st2);
    friend ostream & operator<<(ostream & os, const String &st);
    friend istream & operator>>(istream & is, String & st);
    static int HowMany();
    String operator+(const String &) const;
    String operator+(const char *) const;
    friend String operator+(const char *, const String &);
};

对于实现文件,其他的功能可以沿用string1.cpp,新添加的几个函数需要自定义。

首先,对于重载+运算符,我们分为三个函数。第一个是两个string对象之间的加法,在这里呢,我们可以使用strcat_s函数,直接将两个string对象进行拼接,但是由于默认情况下string对象的最后一个字符都是'\0',所以处理起来比较麻烦,我选择依然使用strcpy_s函数,只是复制的地址不一样,比如说str1的长度为10,str2的长度为10,我们新定义一个str3,要想把str1的内容和str2的内容加起来放进str3中,就把str1的内容从str3的第一个字符处开始赋值,把str2的内容从str3的第11个字符处开始赋值,这样就可以了。对于字符串指针变量的情况,可以完全类似处理。对于字符串指针变量和string对象相加的情况,我们可以人为地进行强制类型转换,将字符串指针变量转换为string对象,再加,那么此时相加就会调用前面定义的两个string对象相加的函数,即可以完成任务。

其次,我们在实现文件中包含头文件<cstring>,然后定义stringow()函数和stringup()函数,分别来对字符串的字母字符进行小写或大写的转换。在转换的时候,我们需要首先对整个字符串进行遍历,然后使用tolower()函数和toupper()函数来进行大小写转换,注意这里this是指针,指向某一个变量时要使用->符号。

最后,我们需要定义has()函数。该函数遍历整个字符串,然后识别输入的特定char类型变量,然后计数。我们在for循环内部嵌套一个if条件判断即可。

实现文件string2.cpp代码如下所示:

// string2.cpp -- String class methods
//

#include "stdafx.h"
#include <cstring>
#include "string2.h"
#include <cctype>
using std::cin;
using std::cout;

int String::num_strings = 0;

int String::HowMany()
{
    return num_strings;
}

String::String(const char * s)
{
    len = std::strlen(s);
    str = new char[len + 1];
    strcpy_s(str, std::strlen(s) + 1, s);
    num_strings++;
}

String::String()
{
    len = 4;
    str = new char[1];
    str[0] = '\0';
    num_strings++;
}

String::String(const String & st)
{
    num_strings++;
    len = st.len;
    str = new char[len + 1];
    strcpy_s(str, std::strlen(st.str) + 1, st.str);
}

String::~String()
{
    --num_strings;
    delete[] str;
}

void String::stringlow()
{
    for (int i = 0; i < this->len + 1; i++)
    {
        this->str[i] = tolower(this->str[i]);
    }
}

void String::stringup()
{
    for (int i = 0; i < this->len + 1; i++)
    {
        this->str[i] = toupper(this->str[i]);
    }
}

int String::has(char x)
{
    int count = 0;
    for (int i = 0; i < this->len + 1; i++)
    {
        if (this->str[i] == x)
            count++;
    }
    return count;
}

String & String::operator=(const String & st)
{
    if (this == &st)
        return *this;
    delete[] str;
    len = st.len;
    str = new char[len + 1];
    strcpy_s(str, std::strlen(st.str) + 1, st.str);
    return *this;
}

String & String::operator=(const char * s)
{
    delete[] str;
    len = std::strlen(s);
    str = new char[len + 1];
    strcpy_s(str, std::strlen(s) + 1, s);
    return *this;
}

char & String::operator[] (int i)
{
    return str[i];
}

const char & String::operator[] (int i) const
{
    return str[i];
}

bool operator<(const String &st1, const String &st2)
{
    return (std::strcmp(st1.str, st2.str) < 0);
}

bool operator>(const String &st1, const String &st2)
{
    return st2 < st1;
}

bool operator==(const String &st1, const String &st2)
{
    return (std::strcmp(st1.str, st2.str) == 0);
}

ostream & operator<<(ostream & os, const String & st)
{
    os << st.str;
    return os;
}

istream & operator>>(istream & is, String & st)
{
    char temp[String::CINLIM];
    is.get(temp, String::CINLIM);
    if (is)
        st = temp;
    while (is &&is.get() != '\n')
        continue;
    return is;
}

String String::operator+(const String & st) const
{
    int total_len = len + st.len;
    char *temp = new char[total_len + 1];
    strcpy_s(temp, len + 1, str);
    strcpy_s(temp + len, st.len + 1, st.str);
    temp[total_len] = '\0';
    return String(temp);
}

String String::operator+(const char * s) const
{
    int total_len = len + strlen(s);
    char *temp = new char[total_len + 1];
    strcpy_s(temp, len + 1, str);
    strcpy_s(temp + len, std::strlen(s) + 1,s);
    temp[total_len] = '\0';
    return String(temp);
}

String operator+(const char * s, const String & st)
{
    return String(s) + st;
}

检验文件题中直接给出,saying2.cpp代码如下所示:

// saying1.cpp -- using expanded String class
#include "stdafx.h"
#include <iostream>
#include "string2.h"
using namespace std;
int main()
{
    String s1(" and I am a C++ student.");
    String s2 = "Please enter your name: ";
    String s3;
    cout << s2;
    cin >> s3;
    s2 = "My name is " + s3;
    cout << s2 << ".\n";
    s2 = s2 + s1;
    s2.stringup();
    cout << "The string\n" << s2 << "\ncontains " << s2.has('A') << " 'A' characters in it.\n";
    s1 = "red";
    String rgb[3] = { String(s1), String("green"), String("blue") };
    cout << "Enter the name of a primary color for mixing light: ";
    String ans;
    bool success = false;
    while (cin >> ans)
    {
        ans.stringlow();
        for (int i = 0; i < 3; i++)
        {
            if (ans == rgb[i])
            {
                cout << "That's right!\n";
                success = true;
                break;
            }
        }
        if (success)
            break;
        else
            cout << "Try again!\n";
    }
    cout << "Bye\n";
    system("pause");
    return 0;
}

运行结果如下图所示:

C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

从运行结果可以看出,该检验文件完成的功能和预期完全一致。

 

3. 新编写程序清单10.7和程序清单10.8描述的Stock类,使之使用动态内存分配的内存,而不是string类对象来存储股票名称。另外,使用重载的operator<<()定义代替show()成员函数。再使用程序清单10.9测试新的定义程序。

本题要求将Stock类进行修改,使用动态内存分配代替string类对象,所以string对象company必须改为char *类型,然后去掉show()函数,改为使用重载的operator<<()来进行输出,该函数我们选择使用友元。

所以头文件stock20.h代码如下:

// stock20.h -- augmented version
#ifndef STOCK20_H_
#define STOCK20_H_
#include <iostream>
using std::ostream;

class Stock
{
private:
    char * company;
    int shares;
    double share_val;
    double total_val;
    void set_tot() { total_val = shares * share_val; }
public:
    Stock();
    Stock(const char * co, long n = 0, double pr = 0.0);
    ~Stock();
    void buy(long num, double price);
    void sell(long num, double price);
    void update(double price);
    friend ostream & operator<<(ostream & os, const Stock &st);
    const Stock & topval(const Stock & s) const;
};

#endif

对于实现文件,当company变量从string对象变成char *类型之后,构造函数那里就必须要改变,必须使用new来动态分配它的内存,而且析构函数必须要delete。对于重载的<<运算符,我们也按照原来的show()函数一样的格式,对ios_base里面的处理不变,只是在此之后,按照标准的重载<<运算符的方式进行输出,同时将cout完全换成我们的输出os。

实现文件stock20.cpp代码如下:

// stock20.cpp -- augnented version
#include "stdafx.h"
#include <iostream>
#include "stock20.h"
using std::ostream;

Stock::Stock()
{
    company = new char[std::strlen("no name") + 1];
    strcpy_s(company, std::strlen("no name") + 1, "no name");
    shares = 0;
    share_val = 0.0;
    total_val = 0.0;
}

Stock::Stock(const char * co, long n, double pr)
{
    company = new char[std::strlen(co) + 1];
    strcpy_s(company, std::strlen(co) + 1, co);
    if (n < 0)
    {
        std::cout << "Number of shares can't be negative; " << company << " shares set to 0.\n";
        shares = 0;
    }
    else
        shares = n;
    share_val = pr;
    set_tot();
}

Stock::~Stock()
{
    delete[] company;
}

void Stock::buy(long num, double price)
{
    if (num < 0)
    {
        std::cout << "Number of shares purchased can't be negative. " << "Transaction is aborted.\n";
    }
    else
    {
        shares += num;
        share_val = price;
        set_tot();
    }
}

void Stock::sell(long num, double price)
{
    using std::cout;
    if (num < 0)
    {
        cout << "Number of shares sold can't be negative. " << "Transaction is aborted.\n";
    }
    else if (num > shares)
    {
        cout << "You can't sell more than you have! " << "Transaction is aborted.\n";
    }
    else
    {
        shares -= num;
        share_val = price;
        set_tot();
    }
}

void Stock::update(double price)
{
    share_val = price;
    set_tot();
}

ostream & operator<<(ostream & os, const Stock &st)
{
    using std::ios_base;
    ios_base::fmtflags orig = os.setf(ios_base::fixed, ios_base::floatfield);
    std::streamsize prec = os.precision(3);

    os << "Company: " << st.company << " Shares: " <<st.shares << "\n";
    os << "Share Price: $" << st.share_val;
    os.precision(2);
    os << " Total Worth: $" << st.total_val << "\n";

    os.setf(orig, ios_base::floatfield);
    os.precision(prec);
    return os;
}

const Stock & Stock::topval(const Stock & s) const
{
    if (s.total_val > total_val)
        return s;
    else
        return *this;
}

检验文件题目要求直接使用程序清单10.9,所以usestock20.cpp代码如下:

// usestock20.cpp -- using the Stock class
// compile with stock20.cpp
#include "stdafx.h"
#include <iostream>
#include "stock20.h"
using std::cout;

const int STKS = 4;
int main()
{
    Stock stocks[STKS] =
    {
        Stock("NanoSmart", 12, 20.0),
        Stock("Boffo Objects", 200, 2.0),
        Stock("Monolithic Obelisks", 130, 3.25),
        Stock("Fleep Enterprises", 60, 6.5)
    };

    std::cout << "Stock holdings:\n";
    int st;
    for (st = 0; st < STKS; st++)
        cout << stocks[st];
    const Stock * top = &stocks[0];
    for (st = 1; st < STKS; st++)
        top = &top->topval(stocks[st]);
    cout << "\nMost valuable holding:\n";
    cout << *top;
    system("pause");
    return 0;
}

运行结果如下图所示:

C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

 

4. 请看下面程序清单10.10定义的Stack类的变量:

(……代码忽略……)

正如私有成员表明的,这个类使用动态内存分配的数组来保存栈项。请重新编写方法,以适应这种新的表示法,并编写一个程序来演示所有的方法,包括复制构造函数和赋值运算符。

本题提供了头文件代码,需要注意的地方在于,本题的私有成员中,定义了一个无符号long类型的指针,对于这种类型的变量,我们同样需要使用new来动态分配内存。

头文件stack.h代码如下:

// stack.h -- class declaration for the stack ADT
#include <iostream>
using std::ostream;
typedef unsigned long Item;

class Stack
{
private:
    enum { MAX = 10 };
    Item * pitems;
    int size;
    int top;
public:
    Stack(int n = MAX);
    Stack(const Stack & st);
    ~Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item & item);
    bool pop(Item & item);
    Stack & operator=(const Stack & st);
    friend ostream & operator<<(ostream & os, const Stack &st);
};

对于实现文件,大部分内容我们可以参考程序清单10.11,而新增的size变量和修改过的pitems对象,我们需要单独编写,且要注意pitems对象必须使用new来动态分配内存,析构函数里面必须将其delete,另外在赋值运算符进行重载时,必须首先将pitems对象进行delete,以防止它的内存已经被占用。

另外我们需要额外编写赋值构造函数,因为要防止初始化时默认构造函数产生二义性;还需要重载<<运算符用来输出。

实现文件stack.cpp代码如下:

// stack.cpp -- functions' definition
#include "stdafx.h"
#include <iostream>
using std::endl;
#include "stack.h"

Stack::Stack(int n)
{
    pitems = new Item[n];
    for (int i = 0; i < n; i++)
    {
        pitems[i] = 0;
    }
    top = 0;
    size = n;
}

Stack::Stack(const Stack & st)
{
    pitems = new Item[st.size];
    for (int i = 0; i < st.size; i++)
    {
        pitems[i] = st.pitems[i];
    }
    top = st.top;
    size = st.size;
}

Stack::~Stack()
{
    delete[] pitems;
}

bool Stack::isempty() const
{
    return top == 0;
}

bool Stack::isfull() const
{
    return top == MAX;
}

bool Stack::push(const Item & item)
{   
    if (top < MAX)
    {
        pitems[top++] = item;
        return true;
    }
    else
        return false;
}

bool Stack::pop(Item & item)
{
    if (top > 0)
    {
        item = pitems[--top];
        return true;
    }
    else
        return false;
}

Stack & Stack::operator=(const Stack & st)
{
    if (this == &st)
        return *this;
    delete[] pitems;
    top = st.top;
    size = st.size;
    pitems = new Item[st.size];
    for (int i = 0; i < st.size; i++)
    {
        pitems[i] = st.pitems[i];
    }
    return *this;
}

ostream & operator<<(ostream & os, const Stack & st)
{
    for (int i = 0; i < st.top; i++)
    {
        os << st.pitems[i] << endl;
    }
    return os;
}

接下来我们可以在程序清单10.12的基础上进行少量修改,就可以检验上面编写的类方法了。对于检验栈是否为空和是否为满,以及入栈出栈,我们都可以完全参考程序清单10.12,下面我们主要检验新的功能,包括使用复制构造函数进行赋值,使用重载的=运算符和<<运算符。

检验文件usestack.cpp代码如下:

// usestack.cpp -- tetsing the Stack class
#include "stdafx.h"
#include <iostream>
#include <cctype>
#include "stack.h"


int main()
{
    using namespace std;
    Stack st;
    char ch;
    unsigned long po;
    cout << "Please enter A to add a purchase order,\n" << "P to process a PO, Q to quit.\n";
    while (cin >> ch && toupper(ch) != 'Q')
    {
        while (cin.get() != '\n')
            continue;
        if (!isalpha(ch))
        {
            cout << '\a';
            continue;
        }
        switch (ch)
        {
        case 'A':
        case 'a': cout << "Enter a PO number to add: ";
            cin >> po;
            if (st.isfull())
                cout << "stack already full.\n";
            else
                st.push(po);
            break;
        case 'p':
        case 'P': if (st.isempty())
            cout << "stack already empty.\n";
                  else
                  {
                      st.pop(po);
                      cout << "PO #" << po << " popped.\n";
                  }
                  break;
        }
        cout << "Please enter A to add a purchase order,\n" << "P to process a PO, or Q to quit.\n";
    }
    cout << "So our stack is:\n" << st;
    Stack st2;
    st2 = st;
    cout << "stack2 = stack is:\n" << st2;
    cout << "Bye\n";
    system("pause");
    return 0;
}

运行结果如下图所示:

C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

从结果图可以看出,我们首先检验了一下程序清单10.12检验的功能,都可以正确运行,接下来我们对栈内数据进行了填充,然后进行了复制构造函数式赋值,以及=运算符赋值,都是正确的。

 

5. Heather银行进行的研究表明,ATM客户不希望排队时间超过1分钟。使用程序清单12.10中的模拟,找出要使平均等候时间为1分钟,每小时到达的客户数应为多少(试验时间不短于100小时)?

首先,我个人认为本题的所谓不希望排队时间不超过1分钟是写错了,应该是不希望排队时间超过1分钟,后面的代码也都是基于这个假设写的。

其次,由于本题涉及的功能完全是程序清单12.10头文件和程序清单12.11实现文件可以完成的,所以头文件我们不需要修改,直接使用即可。

所以头文件queue.h代码如下:

// queue.h -- interface for a queue
#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;

class Queue
{
private:
    struct Node
    {
        Item item;
        struct Node * next;
    };
    enum { Q_SIZE = 10 };
    Node * front;
    Node * rear;
    int items;
    const int qsize;
    Queue(const Queue & q) : qsize(0) { }
    Queue & operator=(const Queue & q)
    {
        return *this;
    }
public:
    Queue(int qs = Q_SIZE);
    ~Queue();
    bool isempty() const;
    bool isfull() const;
    int queuecount() const;
    bool enqueue(const Item &item);
    bool dequeue(Item &item);
};

#endif

实现文件queue.cpp代码如下:

// queue.cpp -- Queue and Customer methods
#include "stdafx.h"
#include "queue.h"
#include <cstdlib>

Queue::Queue(int qs) : qsize(qs)
{
    front = rear = NULL;
    items = 0;
}

Queue::~Queue()
{
    Node * temp;
    while (front != NULL)
    {
        temp = front;
        front = front->next;
        delete temp;
    }
}

bool Queue::isempty() const
{
    return items == 0;
}

bool Queue::isfull() const
{
    return items == qsize;
}

int Queue::queuecount() const
{
    return items;
}

bool Queue::enqueue(const Item &item)
{
    if (isfull())
        return false;
    Node * add = new Node;
    add->item = item;
    add->next = NULL;
    items++;
    if (front == NULL)
        front = add;
    else
        rear->next = add;
    rear = add;
    return true;
}

bool Queue::dequeue(Item &item)
{
    if (front == NULL)
        return false;
    item = front->item;
    items--;
    Node * temp = front;
    front = front->next;
    delete temp;
    if (items == 0)
        rear = NULL;
    return true;
}

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

接下来主要需要修改的就是检验文件了。

首先呢,我们这里假设试验时间不短于100小时,为了简单起见,我就将试验时间定为100小时,接下来我们初始化perhour为1,再对perhour变量进行累加循环,即对每小时到达的客户数量进行累加循环;定义一个avetime变量,表示平均等候时间;使用while语句,判断条件为(perhour++ && avetime <= 1),即从每小时到达客户数为1开始,依次增加每小时到达的客户数,同时满足平均等候时间不超过1分钟,以此作为循环条件。再在循环内部去进行for循环操作。

这里需要注意的是,在for循环之前,我们需要先清空队列,这样才是真正的从完全为空开始进行试验,不然无法控制初始条件下队列中原来就存在的客户数量。

在for循环的最后,我们需要计算一下avetime,即将line_wait除以served。

具体详情请阅读代码,检验文件bank.cpp代码如下:

// bank.cpp -- using the Queue interface
// compile with queue.cpp

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#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;

    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 line(qs);

    cout << "The simulation hours: 100\n";
    int hours = 100;
    long cyclelimit = MIN_PER_HR * hours;

    double perhour;
    double min_per_cust;
    perhour = 1;
    Item temp;
    long turnaways = 0;
    long customers = 0;
    long served = 0;
    long sum_line = 0;
    int wait_time = 0;
    long line_wait = 0;
    double avetime = 0;
    while (perhour++ && avetime <= 1)
    {
        while (!line.isempty())
        {
            line.dequeue(temp);
        }
        min_per_cust = MIN_PER_HR / perhour;
		
        for (int cycle = 0; cycle < cyclelimit; cycle++)
        {
            if (newcustomer(min_per_cust))
            {
                if (line.isfull())
                    turnaways++;
                else
                {
                    customers++;
                    temp.set(cycle);
                    line.enqueue(temp);
                }
            }
            if (wait_time <= 0 && !line.isempty())
            {
                line.dequeue(temp);
                wait_time = temp.ptime();
                line_wait += cycle - temp.when();
                served++;
            }
            if (wait_time > 0)
                wait_time--;
            sum_line += line.queuecount();
        }

        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";
        avetime = (double)line_wait / served;
    }
    cout << "When there comes " << perhour << " people per hour, the average wait time will be about 1 minute.\n";
    cout << "Done!\n";

    system("pause");
    return 0;
}

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

运行结果如下图所示:

C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

在这里我输入的队列最大客户数是10,由于需要输出100组数据,所以我只截了开头和结尾,无法全部显示中间的细节结果。从最后的结果上来看,根据100小时的实验,当每小时到达客户数为25.00时,排队时间刚好不超过1分钟。

 

6. Heather银行想知道,如果再开设一台ATM,情况将如何。请对模拟进行修改,以包含两个队列。假设当第一台ATM前的排队人数少于第二台ATM时,客户将排在第一队,否则将排在第二队。然后再找出要使平均等候时间为1分钟,每小时到达的客户数应该为多少(注意,这是一个非线性问题,即将ATM数量加倍,并不能保证每小时处理的客户数量也翻倍,并确保客户等候的时间少于1分钟)?

本题要求多开设一个ATM,所以我们就会有两个队列,一起进行服务,客户到达之后的排队方式即是,如果第一台人数少于第二台,则排第一队,否则排第二队。所以在这里,头文件和实现文件依然不变,因为本质性功能依然没变。

所以头文件queue.h代码如下:

// queue.h -- interface for a queue
#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;

class Queue
{
private:
    struct Node
    {
        Item item;
        struct Node * next;
    };
    enum { Q_SIZE = 10 };
    Node * front;
    Node * rear;
    int items;
    const int qsize;
    Queue(const Queue & q) : qsize(0) { }
    Queue & operator=(const Queue & q)
    {
        return *this;
    }
public:
    Queue(int qs = Q_SIZE);
    ~Queue();
    bool isempty() const;
    bool isfull() const;
    int queuecount() const;
    bool enqueue(const Item &item);
    bool dequeue(Item &item);
};

#endif

实现文件queue.cpp代码如下:

// queue.cpp -- Queue and Customer methods
#include "stdafx.h"
#include "queue.h"
#include <cstdlib>

Queue::Queue(int qs) : qsize(qs)
{
    front = rear = NULL;
    items = 0;
}

Queue::~Queue()
{
    Node * temp;
    while (front != NULL)
    {
        temp = front;
        front = front->next;
        delete temp;
    }
}

bool Queue::isempty() const
{
    return items == 0;
}

bool Queue::isfull() const
{
    return items == qsize;
}

int Queue::queuecount() const
{
    return items;
}

bool Queue::enqueue(const Item &item)
{
    if (isfull())
        return false;
    Node * add = new Node;
    add->item = item;
    add->next = NULL;
    items++;
    if (front == NULL)
        front = add;
    else
        rear->next = add;
    rear = add;
    return true;
}

bool Queue::dequeue(Item &item)
{
    if (front == NULL)
        return false;
    item = front->item;
    items--;
    Node * temp = front;
    front = front->next;
    delete temp;
    if (items == 0)
        rear = NULL;
    return true;
}

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

接下来我们着重修改检验文件。

首先,本题有两台ATM,所以我们需要两个Queue对象,分别称为line1和line2,接下来的处理方法和上一题类似,我们假设试验时间为100小时,初始化perhour为1,然后自定义avetime,对perhour进行累加循环,同时判断avetime <= 1;但是这里需要注意,我们现在是两个ATM同时服务,所以到达的客户需要有一个选择,即排哪个队,根据题目要求,我们肯定需要有两个line_size和wait_time,所以定义wait_time1和wait_time2分别表示队列1和队列2的等候时间,定义line1_size和line2_size分别表示队列1和队列2的尺寸。

在循环内部,我们首先依然还是要清空队列,这里就要清空两次了;然后在for循环内部,当有客户到达时,判断是否turnaway就需要去判断两个队列了;如果不满足turnaway的条件,就比较line1_size和line2_size,来决定到达的客户排哪个队列;后面判断出队和计算sum_line,注意都需要进行两次。

其他操作和上题相同,注意有些需要操作两次即可。

具体详情请阅读代码,检验文件bank.cpp代码如下:

// bank.cpp -- using the Queue interface
// compile with queue.cpp

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#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;

    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 line1(qs);
    Queue line2(qs);

    cout << "The simulation hours: 100\n";
    int hours = 100;
    long cyclelimit = MIN_PER_HR * hours;

    double perhour;
    double min_per_cust;
    perhour = 1;
    Item temp;
    long turnaways = 0;
    long customers = 0;
    long served = 0;
    long sum_line = 0;
    int wait_time1 = 0;
    int wait_time2 = 0;
    int line1_size = 0;
    int line2_size = 0;
    long line_wait = 0;
    double avetime = 0;

    while (perhour++ && avetime <= 1)
    {
        while (!line1.isempty())
        {
            line1.dequeue(temp);
        }
        while (!line2.isempty())
        {
            line2.dequeue(temp);
        }
        min_per_cust = MIN_PER_HR / perhour;

        for (int cycle = 0; cycle < cyclelimit; cycle++)
        {
            if (newcustomer(min_per_cust))
            {
                if (line1.isfull() && line2.isfull())
                    turnaways++;
                else if(line1_size < line2_size)
                {
                    customers++;
                    temp.set(cycle);
                    line1.enqueue(temp);
                    line1_size++;
                }
                else
                {
                    customers++;
                    temp.set(cycle);
                    line2.enqueue(temp);
                    line2_size++;
                }
            }
            if (wait_time1 <= 0 && !line1.isempty())
            {
                line1.dequeue(temp);
                line1_size--;
                wait_time1 = temp.ptime();
                line_wait += cycle - temp.when();
                served++;
            }
            if (wait_time2 <= 0 && !line2.isempty())
            {
                line2.dequeue(temp);
                line2_size--;
                wait_time2 = temp.ptime();
                line_wait += cycle - temp.when();
                served++;
            }
            if (wait_time1 > 0)
                wait_time1--;
            if (wait_time2 > 0)
                wait_time2--;
            sum_line += line1.queuecount();
            sum_line += line2.queuecount();
        }

        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";
        avetime = (double)line_wait / served;
    }
    cout << "When there comes " << perhour << " people per hour, the average wait time will be about 1 minute.\n";
    cout << "Done!\n";

    system("pause");
    return 0;
}

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

运行结果如下图所示:

C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

C++ Primer Plus(第六版)编程练习答案 第12章 类和动态内存分配

从结果上可以看出,当只有1台ATM时,每小时到达客户数为25时,平均等候时间为1分钟,而两台ATM时,每小时到达客户数为60,平均等候时间为1分钟,所以效果不止翻倍。

 

本章所有编程练习的工程源码可在此处下载(点击此链接下载),供大家参考交流!