53 C++ Primer Plus(第六版)第十二章 编程练习答案
1
Cow.h
#pragma once
#include<iostream>
using namespace std;
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;
};
exercise01_Cow.cpp
#include<iostream>
#include"Cow.h"
using namespace std;
Cow::Cow()
{
name[0] = '\0';
hobby = new char[1];
hobby[0] = '\0';
//hobby = nullptr;
weight = 0;
}
Cow::Cow(const char* nm, const char* ho, double wt)
{
strcpy_s(name, 20, nm);
int len = strlen(ho);
hobby = new char[len + 1];
strcpy_s(hobby, len + 1, ho);
weight = wt;
}
Cow::Cow(const Cow& c)
{
strcpy_s(name, 20, c.name);
int len = strlen(c.hobby);
hobby = new char[len + 1];
strcpy_s(hobby, len + 1, c.hobby);
weight = c.weight;
}
Cow::~Cow()
{
delete[] hobby;
}
Cow& Cow::operator=(const Cow& c)
{
if (this == &c)
return *this;
delete[] hobby;
strcpy_s(name, 20, c.name);
int len = strlen(c.hobby);
hobby = new char[len + 1];
strcpy_s(hobby, len + 1, c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow() const
{
cout << "name: " << name << "\t"
<< "hobby: " << hobby << "\t"
<< "weight: " << weight << endl;
}
exercise01.cpp
#include<iostream>
#include"Cow.h"
using namespace std;
int main()
{
Cow c1;
c1.ShowCow();
cout << "-----------------\n";
Cow c2("Happy", "every day!", 10);
c2.ShowCow();
cout << "-----------------\n";
Cow c3(c2);
c3.ShowCow();
Cow c4 = c3;
c4.ShowCow();
cout << "-----------------\n";
return 0;
}
2
string2.h
// string2.h -- fixed and augmented string class definition
#ifndef STRING1_H_
#define STRING1_H_
#include <iostream>
using std::ostream;
using std::istream;
class String
{
private:
char * str; // pointer to string
int len; // length of string
static int num_strings; // number of objects
static const int CINLIM = 80; // cin input limit
public:
// constructors and other methods
String(const char * s); // constructor
String(); // default constructor
String(const String &); // copy constructor
~String(); // destructor
int length () const { return len; }
// overloaded operator methods
String & operator=(const String &);
String & operator=(const char *);
char & operator[](int i);
const char & operator[](int i) const;
// overloaded operator friends
friend bool operator<(const String &st, 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 function
static int HowMany();
friend String operator+(const String& st1, const String& st2);
void Stringlow();
void Stringup();
int charnum(char c);
};
#endif
exercise02_string2.cpp
// string1.cpp -- String class methods
#include<iostream>
#include <cstring> // string.h for some
#include "string2.h" // includes <iostream>
using namespace std;
// initializing static class member
int String::num_strings = 0;
// static method
int String::HowMany()
{
return num_strings;
}
// class methods
String::String(const char * s) // construct String from C string
{
len = std::strlen(s); // set size
str = new char[len + 1]; // allot storage
strcpy_s(str,len + 1, s); // initialize pointer
//strcpy(str, s);
num_strings++; // set object count
}
String::String() // default constructor
{
len = 4;
str = new char[1];
str[0] = '\0'; // default string
num_strings++;
}
String::String(const String & st)
{
num_strings++; // handle static member update
len = st.len; // same length
str = new char [len + 1]; // allot space
strcpy_s(str, len + 1, st.str); // copy string to new location
//std::strcpy(str, st.str);
}
String::~String() // necessary destructor
{
--num_strings; // required
delete [] str; // required
}
// overloaded operator methods
// assign a String to a String
String & String::operator=(const String & st)
{
if (this == &st)
return *this;
delete [] str;
len = st.len;
str = new char[len + 1];
strcpy_s(str, len + 1, st.str);
//std::strcpy(str, st.str);
return *this;
}
// assign a C string to a String
String & String::operator=(const char * s)
{
delete [] str;
len = std::strlen(s);
str = new char[len + 1];
strcpy_s(str, len + 1, s);
//std::strcpy(str, s);
return *this;
}
// read-write char access for non-const String
char & String::operator[](int i)
{
return str[i];
}
// read-only char access for const String
const char & String::operator[](int i) const
{
return str[i];
}
// overloaded operator friends
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);
}
// simple String output
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 operator+(const String& st1, const String& st2)
{
String s;
s.len = st1.len + st2.len;
s.str = new char[s.len + 1];
strcpy_s(s.str, st1.len + 1, st1.str);
strcat_s(s.str, s.len + 1, st2.str); //第二个参数是总字符串长度
return s;
}
void String::Stringlow()
{
for (int i = 0; i < len; i++)
{
if (isupper(str[i]))
str[i] = tolower(str[i]);
}
}
void String::Stringup()
{
for (int i = 0; i < len; i++)
{
if (islower(str[i]))
str[i] = toupper(str[i]);
}
}
int String::charnum(char c)
{
int num = 0;
for (int i = 0; i < len; i++)
{
if (str[i] == c)
num++;
}
return num;
}
exercise02.cpp
//主程序,即书中测试代码
#include <iostream>
using namespace std;
#include "String2.h"
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.charnum('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";
return 0;
}
3
stock20.h
// stock20.h -- augmented version
#ifndef STOCK20_H_
#define STOCK20_H_
#include <string>
#include<iostream>
class Stock
{
private:
char* company;
int shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val; }
public:
Stock(); // default constructor
Stock(const char* co, long n = 0, double pr = 0.0);
~Stock(); // do-nothing destructor
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
//void show()const;
const Stock & topval(const Stock & s) const;
friend std::ostream& operator<<(std::ostream& os, const Stock& s);
};
#endif
exercise03_stock20.cpp
// stock20.cpp -- augmented version
#include <iostream>
#include "stock20.h"
using namespace std;
// constructors
Stock::Stock() // default constructor
{
company = new char[1];
company[0] = '\0';
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(const char* co, long n, double pr)
{
int len = strlen(co);
company = new char[len + 1];
strcpy_s(company, len + 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();
}
// class destructor
Stock::~Stock() // quiet class destructor
{
}
// other methods
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& s)
{
using std::cout;
using std::ios_base;
// set format to #.###
ios_base::fmtflags orig =
cout.setf(ios_base::fixed, ios_base::floatfield);
std::streamsize prec = cout.precision(3);
os << "Company: " << s.company
<< " Shares: " << s.shares << '\n';
os << " Share Price: $" << s.share_val;
// set format to #.##
cout.precision(2);
os << " Total Worth: $" << s.total_val << '\n';
// restore original format
cout.setf(orig, ios_base::floatfield);
cout.precision(prec);
return os;
}
const Stock & Stock::topval(const Stock & s) const
{
if (s.total_val > total_val)
return s;
else
return *this;
}
exercise03_usestok2.cpp
// usestok2.cpp -- using the Stock class
// compile with stock20.cpp
#include <iostream>
#include "stock20.h"
const int STKS = 4;
int main()
{
{
// create an array of initialized objects
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++)
std::cout << stocks[st];
//stocks[st].show();
// set pointer to first element
const Stock * top = &stocks[0];
for (st = 1; st < STKS; st++)
top = &top->topval(stocks[st]);
// now top points to the most valuable holding
std::cout << "\nMost valuable holding:\n";
std::cout << *top << std::endl;
//top->show();
}
// std::cin.get();
return 0;
}
4
stack.h
// stack.h -- class definition for the stack ADT
#include<iostream>
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Item* pitems;
int size; //number of elements in stack
int top; // index for top stack item
public:
Stack(int n = MAX); //creat stack with n elements
Stack(const Stack& st);
~Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item & item); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item & item); // pop top into item
Stack& operator=(const Stack& st);
friend std::ostream& operator<<(std::ostream& os, const Stack& st);
};
#endif
exercise04_stack.cpp
// stack.cpp -- Stack member functions
#include "stack.h"
Stack::Stack(int n) //creat stack with n elements
{
size = n;
pitems = new Item[n];
top = 0;
}
Stack::Stack(const Stack& st)
{
size = st.size;
pitems = new Item[size + 1];
for (top = 0; top < size; top++)
pitems[top] = st.pitems[top];
}
Stack::~Stack()
{
delete[] pitems;
pitems = nullptr;
size = top = 0;
}
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;
size = st.size;
pitems = new Item[size + 1];
for (top = 0; top < size; top++)
pitems[top] = st.pitems[top];
return *this;
}
exercise04_stacker.cpp
// stacker.cpp -- testing the Stack class
#include <iostream>
#include <cctype> // or ctype.h
#include "stack.h"
int main()
{
using namespace std;
Stack st; // create an empty stack
cout << "Is Stack st empty?\n";
cout << st.isempty() << endl;
cout << "Is Stack st full?\n";
cout << st.isfull() << endl;
cout << "-------------------\n";
Item it[10];
cout << "Push to st:\n";
for (int i = 0; i < 10; i++)
{
it[i] = i + 1;
st.push(it[i]);
cout << it[i] << endl;
}
cout << "Is Stack st full?\n";
cout << st.isfull() << endl;
cout << "Is Stack st empty?\n";
cout << st.isempty() << endl;
cout << "-------------------\n";
cout << "Pop to st:\n";
for (int i = 0; i < 10; i++)
{
st.pop(it[i]);
cout << it[i] << endl;
}
cout << "Is Stack st full?\n";
cout << st.isfull() << endl;
cout << "Is Stack st empty?\n";
cout << st.isempty() << endl;
cout << "-------------------\n";
Stack st2;
cout << "Is Stack st2 full?\n";
cout << st2.isfull() << endl;
cout << "Is Stack st2 empty?\n";
cout << st2.isempty() << endl;
cout << "-------------------\n";
st2 = st;
cout << "Is Stack st2 full?\n";
cout << st2.isfull() << endl;
cout << "Is Stack st2 empty?\n";
cout << st2.isempty() << endl;
cout << "-------------------\n";
cout << "Pop to st2:\n";
for (int i = 0; i < 10; i++)
{
st2.pop(it[i]);
cout << it[i] << endl;
}
cout << "Is Stack st2 full?\n";
cout << st2.isfull() << endl;
cout << "Is Stack st2 empty?\n";
cout << st2.isempty() << endl;
cout << "-------------------\n";
return 0;
}
5
队列长度10,每小时客户数18时,平均等待时间1分钟。
6
queue2.h
// queue.h -- interface for a queue
#ifndef QUEUE_H_
#define QUEUE_H_
// This queue will contain Customer items
class Customer
{
private:
long arrive; // arrival time for customer
int processtime; // processing time for customer
public:
Customer() : arrive(0), processtime (0){}
void set(long when);
long when() const { return arrive; }
int ptime() const { return processtime; }
};
typedef Customer Item;
class Queue
{
private:
// class scope definitions
// Node is a nested structure definition local to this class
struct Node { Item item; struct Node * next;};
enum {Q_SIZE = 10};
// private class members
Node * front; // pointer to front of Queue
Node * rear; // pointer to rear of Queue
int items; // current number of items in Queue
const int qsize; // maximum number of items in Queue
// preemptive definitions to prevent public copying
Queue(const Queue & q) : qsize(0) { }
Queue & operator=(const Queue & q) { return *this;}
public:
Queue(int qs = Q_SIZE); // create queue with a qs limit
~Queue();
bool isempty() const;
bool isfull() const;
int queuecount() const;
bool enqueue(const Item &item); // add item to end
bool dequeue(Item &item); // remove item from front
friend bool operator>(const Queue& item1, const Queue& item2);
};
#endif
exercise06_queue2.cpp
// queue.cpp -- Queue and Customer methods
#include "queue2.h"
#include <cstdlib> // (or stdlib.h) for rand()
// Queue methods
Queue::Queue(int qs) : qsize(qs)
{
front = rear = NULL; // or nullptr
items = 0;
}
Queue::~Queue()
{
Node * temp;
while (front != NULL) // while queue is not yet empty
{
temp = front; // save address of front item
front = front->next;// reset pointer to next item
delete temp; // delete former front
}
}
bool Queue::isempty() const
{
return items == 0;
}
bool Queue::isfull() const
{
return items == qsize;
}
int Queue::queuecount() const
{
return items;
}
// Add item to queue
bool Queue::enqueue(const Item & item)
{
if (isfull())
return false;
Node * add = new Node; // create node
// on failure, new throws std::bad_alloc exception
add->item = item; // set node pointers
add->next = NULL; // or nullptr;
items++;
if (front == NULL) // if queue is empty,
front = add; // place item at front
else
rear->next = add; // else place at rear
rear = add; // have rear point to new node
return true;
}
// Place front item into item variable and remove from queue
bool Queue::dequeue(Item & item)
{
if (front == NULL)
return false;
item = front->item; // set item to first item in queue
items--;
Node * temp = front; // save location of first item
front = front->next; // reset front to next item
delete temp; // delete former first item
if (items == 0)
rear = NULL;
return true;
}
// customer method
// when is the time at which the customer arrives
// the arrival time is set to when and the processing
// time set to a random value in the range 1 - 3
void Customer::set(long when)
{
processtime = std::rand() % 3 + 1;
arrive = when;
}
bool operator>(const Queue& item1, const Queue& item2)
{
return item1.items > item2.items;
/*if (item1.items >= item2.items)
return true;
else
return false;*/
}
exercise06_bank.cpp
// bank.cpp -- using the Queue interface
// compile with queue.cpp
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
#include "queue2.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x); // is there a new customer?
int main()
{
using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
// setting things up
std::srand(std::time(0)); // random initializing of rand()
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maximum size of queue: ";
int qs; //队列最大长度
cin >> qs;
Queue line1(qs); // line queue holds up to qs people
Queue line2(qs);
cout << "Enter the number of simulation hours: ";
int hours; // hours of simulation,程序模拟持续时间,单位小时
cin >> hours;
// simulation will run 1 cycle per minute
long cyclelimit = MIN_PER_HR * hours; // # of cycles
cout << "Enter the average number of customers per hour: ";
double perhour; // average # of arrival per hour,平均每小时客户数
cin >> perhour;
double min_per_cust; // average time between arrivals
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 queue
long served = 0; // served during the simulation
long sum_line = 0; // cumulative line length
int wait_time1 = 0; // time until autoteller is free
int wait_time2 = 0;
long line_wait1 = 0; // cumulative time in line
long line_wait2 = 0;
// running the simulation
for (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust)) // have newcomer
{
if (line1.isfull() && line2.isfull()) //两个队列都满了,拒绝加入队列
turnaways++; //被拒绝的人数
else if(line2 > line1 || line2.isfull())
{
customers++;
temp.set(cycle); // cycle = time of arrival
line1.enqueue(temp); // add newcomer to line
}
else
{
customers++;
temp.set(cycle); // cycle = time of arrival
line2.enqueue(temp); // add newcomer to line
}
}
if (wait_time1 <= 0 && !line1.isempty())
{
line1.dequeue (temp); // attend next customer
wait_time1 = temp.ptime(); // for wait_time minutes
line_wait1 += cycle - temp.when();
served++;
}
if (wait_time2 <= 0 && !line2.isempty())
{
line2.dequeue(temp); // attend next customer
wait_time2 = temp.ptime(); // for wait_time minutes
line_wait2 += cycle - temp.when();
served++;
}
if (wait_time1 > 0)
wait_time1--;
sum_line += line1.queuecount();
if (wait_time2 > 0)
wait_time2--;
sum_line += line2.queuecount(); //队伍总长度
}
// reporting results
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_wait1 + line_wait2) / served << " minutes\n";
}
else
cout << "No customers!\n";
cout << "Done!\n";
// cin.get();
// cin.get();
return 0;
}
// x = average time, in minutes, between customers
// return value is true if customer shows up this minute
bool newcustomer(double x)
{
return (std::rand() * x / RAND_MAX < 1);
}