📄 selsolutions5.txt
字号:
{
int ct = 0;
char * ps = str;
while (*ps)
{
if (*ps++ == ch)
++ct;
}
return ct;
}
int operator==(const String & s1, const String & s2)
{
if (s1.chars != s2.chars)
return 0;
else if (std::strcmp(s1.str, s2.str) == 0)
return 1;
else
return 0;
}
int operator<(const String & s1, const String & s2)
{
if (std::strcmp(s1.str, s2.str) < 0)
return 1;
else
return 0;
}
int operator>(const String & s1, const String & s2)
{
if (std::strcmp(s1.str, s2.str) > 0)
return 1;
else
return 0;
}
PE 12-4
// pe12stak.h -- class definition for the stack ADT
#ifndef PE12STAK_H_
#define PE12STAK_H_
typedef unsigned long Item;
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Item * pitems; // holds stack items
int size; // max number of elements in stack
int top; // index for top stack item
Stack(const Stack & st) { } // no copying of stacks
Stack & operator=(const Stack & st) { return *this; } // no assignment
public:
Stack(int n = MAX);
~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
};
#endif
// pe12stak.cpp -- Stack member functions
#include "pe12stak.h"
Stack::Stack(int n) // create an empty stack
{
size = n;
pitems = new Item [size];
top = 0;
}
Stack::~Stack() { delete [] pitems; }
bool Stack::isempty() const
{
return top == 0 ? true: false;
}
bool Stack::isfull() const
{
return top == size ? true: false;
}
bool Stack::push(const Item & item)
{
if (top < size)
{
pitems[top++] = item;
return true;
}
else
return false;
}
bool Stack::pop(Item & item)
{
if (top > 0)
{
item = pitems[--top];
return true;
}
else
return false;
}
// pe12-4.cpp
#include <iostream>
#include <cctype>
#include "pe12stak.h" // modified to define customer structure
// link with pe12stak.cpp
int main(void)
{
using namespace std;
Stack st(3); // create a stack of po numbers
unsigned long temp;
char c;
cout << "Please enter A to add a PO,\n"
<< "P to process a PO, and Q to quit.\n";
while (cin >> c && (c = toupper(c)) != 'Q')
{
while (cin.get() != '\n')
continue;
if (c != 'A' && c != 'P')
{
cout << "Please respond with A, P, or Q: ";
continue;
}
switch (c)
{
case 'A': if (st.isfull())
cout << "stack already full\n";
else
{
cout << "Enter PO number: ";
cin >> temp;
st.push(temp);
}
break;
case 'P': if (st.isempty())
cout << "stack already empty\n";
else {
st.pop(temp);
cout << "Processing PO " << temp << '\n';
}
break;
default: cout << "Whoops! Programming error!\n";
}
cout << "Please enter A to add a customer,\n"
<< "P to process a customer, and Q to quit.\n";
}
cout << "Done!\n";
return 0;
}
PE 12-6
// pe12que.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 = 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
};
#endif
// pe12que.cpp -- Queue and Customer methods
#include "pe12que.h"
#include <cstdlib> // (or stdlib.h) for rand()
using std::rand;
// Queue methods
Queue::Queue(int qs) : qsize(qs)
{
front = rear = NULL;
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
if (add == NULL)
return false; // quit if none available
add->item = item; // set node pointers
add->next = NULL;
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;
}
// pe12-6.cpp -- use the Queue interface
// link to pe12que.cpp
// modify Listing 12.10 by adding a second queue
#include <iostream>
#include <ctime> // for time()
#include <cstdlib> // for rand() and srand()
#include "pe12que.h"
const long MIN_PER_HR = 60L;
bool newcustomer(double x); // is there a new customer?
int main(void)
{
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 each queue: ";
int qs;
cin >> qs;
Queue line1(qs); // line queue holds up to qs people
Queue line2(qs); // second queue
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
Item temp; // new customer data
long turnaways; // turned away by full queue
long customers; // joined the queue
long served; // served during the simulation
long sum_line; // cumulative line length
int wait_time1; // time until autoteller1 is free
int wait_time2; // time until autoteller2 is free
long line_wait; // cumulative time in line
double min_per_cust; // average time between arrivals
cout << "Enter the average number of customers per hour: ";
double perhour; // average # of arrival per hour
cin >> perhour;
while ( perhour > 0 ) // begin new loop
{
min_per_cust = MIN_PER_HR / perhour;
turnaways = 0;
customers = 0;
served = 0;
sum_line = 0;
wait_time1 = wait_time2 = 0;
line_wait = 0;
// running the simulation
for (long cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust)) // have newcomer
{
if (line1.isfull() && line2.isfull())
turnaways++;
else // at least one line is not full
{
customers++;
temp.set(cycle); // cycle = time of arrival
// add customer to shorter line
if (line1.queuecount() <= line2.queuecount())
line1.enqueue(temp); // add newcomer to line1
else
line2.enqueue(temp); // add newcomer to line2
}
}
// process customers in first queue
if (wait_time1 <= 0 && !line1.isempty())
{
line1.dequeue (temp); // attend next customer
wait_time1 = temp.ptime(); // for wait_time minutes
line_wait += cycle - temp.when();
served++;
}
if (wait_time1 > 0)
wait_time1--;
sum_line += line1.queuecount();
// process customers in second queue
if (wait_time2 <= 0 && !line2.isempty())
{
line2.dequeue (temp); // attend next customer
wait_time2 = temp.ptime(); // for wait_time minutes
line_wait += cycle - temp.when();
served++;
}
if (wait_time2 > 0)
wait_time2--;
sum_line += line2.queuecount();
}
// reporting results
if (customers > 0)
{
cout << "customers accepted: " << customers << '\n';
cout << " customers served: " << served << '\n';
cout << " turnaways: " << turnaways << '\n';
cout << "average queue size: ";
cout.precision(2);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout.setf(ios_base::showpoint);
cout << (double) sum_line / cyclelimit << '\n';
cout << " average wait time: "
<< (double) line_wait / served << " minutes\n";
}
else
cout << "No customers!\n";
// clear queues
while (!line1.isempty())
line1.dequeue(temp);
while (!line2.isempty())
line2.dequeue(temp);
cout << "Enter new value for customers per hour (0 to quit): ";
cin >> perhour;
} // end of new loop
cout << "Bye\n";
return 0;
}
// x = average time, in minutes, between customers
// return value is true if customer shows up this minute
bool newcustomer(double x)
{
if (std::rand() * x / RAND_MAX < 1)
return true;
else
return false;
}
Chapter 13
PE 13-1
// cd.h -- base class
#ifndef CD_H_
#define CD_H_
class Cd { // represents a CD disk
private:
char performers[50];
char label[20];
int selections; // number of selections
double playtime; // playing time in minutes
public:
Cd(const char * s1, const char * s2, int n, double x);
// Cd(const Cd & d); // default version is fine
Cd();
virtual ~Cd() {}
virtual void Report() const; // reports all CD data
// Cd & operator=(const Cd & d); // default version is fine
};
#endif
// pe13-1cd.cpp -- cd methods
#include <iostream>
#include <cstring>
#include "cd.h"
Cd::Cd(const char * s1, const char * s2, int n, double x)
{
std::strncpy(performers, s1, 49);
performers[49] = '\0';
std::strncpy(label, s2, 19);
label[19] = '\0';
selections = n;
playtime = x;
}
Cd::Cd()
{
performers[0] = '\0';
label[0] = '\0';
selections = 0;
playtime = 0.0;
}
void Cd::Report() const
{
using std::cout;
using std::endl;
cout << "Performer(s): " << performers << endl;
cout << "Label: " << label << endl;
cout << "Number of selections: " << selections << endl;
cout << "Play time: " << playtime << endl;
}
// classic.h
// derived class
#ifndef CLASSIC_H_
#define CLASSIC_H_
#include "cd.h"
class Classic : public Cd
{
private:
char primarywork[50];
public:
Classic(const char * pw, const char * s1, const char * s2,
int n, double x);
Classic();
void Report() const; // redefine to report primary work
};
#endif
// pe13-1cl.cpp
// Classic methods
#include <iostream>
#include <cstring>
#include "classic.h"
Classic::Classic(const char * pw, const char * s1,
const char * s2, int n, double x)
: Cd(s1, s2, n, x)
{
std::strncpy(primarywork, pw, 49);
primarywork[49] = '\0';
}
Classic::Classic() : Cd()
{
primarywork[0] = '\0';
}
void Classic::Report() const
{
std::cout << "Primary work: " << primarywork << std::endl;
Cd::Report();
}
// pe13-1.cpp
#include <iostream>
using namespace std;
#include "classic.h" // which will contain #include cd.h
void Bravo(const Cd & disk);
int main()
{
Cd c1("Beatles", "Capitol", 14, 35.5);
Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C",
"Alfred Brendel", "Philips", 2, 57.17);
Cd *pcd = &c1;
cout << "Using object directly:\n";
c1.Report(); // use Cd method
c2.Report(); // use Classic method
cout << "Using type cd * pointer to objects:\n";
pcd->Report(); // use Cd method for cd object
pcd = &c2;
pcd->Report(); // use Classic method for classic object
cout << "Calling a function with a Cd reference argument:\n";
Bravo(c1);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -