C++ Primer Plus(第六版)第十二章课后习题

C++ Primer Plus(第六版)第十二章课后习题

12.10.1

12.10.1.h
#ifndef DH
#define DH
class Cow
{
char name[20];
char * hobby;
double weight;
public:
Cow();
Cow(const char * nm, const char *bo,double wt);
Cow(const Cow &c);
~Cow();
Cow & operator=(const Cow & c);
void ShowCow() const;
};
#endif

12.10.1.cpp
#include
#include “12.10.1.h”
Cow::Cow()
{

strcpy(name,"Default");
hobby=new char[3];
strcpy(hobby,"No");
weight=0;

}
Cow::Cow(const char * nm, const char *bo,double wt)
{
strcpy(name,nm);
hobby=new char [std::strlen(bo)+1];
strcpy(hobby,bo);
weight=wt;
}
Cow::Cow(const Cow &c)
{
strcpy(name,c.name);
hobby=new char [std::strlen(c.hobby)+1];
strcpy(hobby,c.hobby);
weight=c.weight;
}
Cow::~Cow()
{
delete [] hobby;
}
Cow & Cow::operator=(const Cow & c)
{
strcpy(name,c.name);
hobby=new char [std::strlen(c.hobby)+1];
strcpy(hobby,c.hobby);
weight=c.weight;
return *this;
}
void Cow::ShowCow() const
{
using std::cout;
cout << "Cow’s name is " << name << “;\n”
<< "hobby is " << hobby << “;\n”
<< "weight is : "<< weight << “.\n”;
}

main.cpp
#include
#include “12.10.1.h”
int main()
{
Cow a;
a.ShowCow();
Cow b(“Lily”,“Cookie”,500);
b.ShowCow();
Cow c;
c=b;
c.ShowCow();
Cow d(b);
d.ShowCow();
}

12.10.2

string2.h
#ifndef STRING1_H_
#define STRING1_H_
#include
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;}
String & operator=(const String &);
String & operator=(const char*);
char & operator[](int i);
const char & operator[] (int i) const;
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 String operator+(const String & st1, const String & st2);
void Stringlow();
void Stringup();
int has(const char ch);
friend std::ostream &operator<<(std::ostream &os,const String &st);
friend std::istream &operator>>(std::istream &is,String & st);
static int Howmany();
};
#endif

string2.cpp
#include
#include
#include “string2.h”
#include
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];
std::strcpy(str,s);
num_strings++;
}
String::String()
{
len=1;
str=new char[1];
str[0]=’\0’;
num_strings++;
}
String::String(const String &st)
{
num_strings++;
len=st.len;
str=new char[len+1];
std::strcpy(str,st.str);
}
String::~String()
{
–num_strings;
delete []str;
}
String &String::operator=(const String &st)
{
if (this==&st)
return *this;
delete [] str;
len=st.len;
str=new char[len+1];
std::strcpy(str,st.str);
return this;
}
String &String::operator=(const char
s)
{
delete [] str;
len=std::strlen(s);
str=new char[len+1];
std::strcpy(str,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 st2>st1;
}
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);
}
String operator+(const String & st1, const String & st2)
{
String temp;
temp.len = st1.len + st2.len;
temp.str = new char [temp.len + 1];
strcpy(temp.str,st1.str);
strcat(temp.str,st2.str);
return temp;
}
void String::Stringlow()
{
for(int i=0;i<len;i++)
str[i]=tolower(str[i]);
}
void String::Stringup()
{
for(int i=0;i<len;i++)
str[i]=toupper(str[i]);
}
int String::has(const char ch)
{
int j=0;
for(int i=0;i<len;i++)
if(str[i]==ch)
j++;
return j;
}
std::ostream & operator << (std::ostream & os ,const String &st)
{
os << st.str;
return os;
}
std::istream & operator >> (std::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;
}

pel2_2.cpp

#include
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 ; //"My name is “被自动转变为String型
cout << s2 << “.\n”;
s2=s2+s1;
s2.Stringup();
cout << “The string\n” << s2 << “\ncontains " << s2.has(‘A’)
<<” ‘A’ charactors in it.\n”;
s1= “red”;
String rgb[3]={String (s1),String (“greeen”),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;
}

12.10.3

stock20.h
#ifndef STOCK20_H_
#define STOCK20_H_
#include
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 std::ostream & operator << (std::ostream &os,const Stock & s);
const Stock & topval(const Stock & s) const;
};
#endif

stock20.cpp
#include
#include “stock20.h”
Stock::Stock()
{
int len;
len=strlen(“no name”);
company=new char[len+1];
strcpy(company,“no name”);
shares=0;
share_val=0.0;
total_val=0.0;
}

Stock::Stock(const char co[],long n,double pr)
{
int len;
len=strlen(co);
company=new char[len+1];
strcpy(company,co);
if (n<0)
{
std::cout << “Number of shares can’t be nagetive:”
<< company << " shares set to 0.\n";
shares=0;
}
else
shares=n;
share_val=pr;
set_tot();
}

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

usestock.cpp
#include
#include “stock20.h”
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++)
std::cout << stocks[st];
const Stock * top=&stocks[0];
for(st=1;st<STKS;st++)
top=&top->topval(stocks[st]);
std::cout << “\nMost valueable holding:\n”;
std::cout << *top;
return 0;
}

10.10(此处提供12.10.4需要的程序10.10)

stack.h
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;

class Stack
{
private:
enum{MAX=10};
Item items[MAX];
int top;
public:
Stack();
bool isempty() const;
bool isfull() const;
bool push(const Item &item);
bool pop(Item &item);
};
#endif

stack.cpp
#include “stack.h”
Stack::Stack()
{
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)
{
items[top++]=item;
return true;
}
else
return false;
}

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

stacker.cpp
#include
#include
#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,or 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 << “Bye\n”;
return 0;
}

12.10.4

stack.h
#ifndef STACK_H_
#define STACK_H_
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);
};
#endif

stack.cpp
#include
#include “stack.h”
Stack::Stack(int n)
{
size=n;
pitems=new Item [size];
top=0;
}

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

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)
{
size=st.size;
pitems=new Item [size];
for(int i=0;i<size;i++)
pitems[i]=st.pitems[i];
top=0;
return *this;
}

stacker.cpp
#include
#include
#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,or 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 << “Bye\n”;
return 0;
}

12.11(此处提供12.10.5, 12.10.6需要的程序12.11)

此题对于初学者理解非常困难,可以先忽略12.10.5, 12.10.6题,如果觉得吃力可以直接前往13章,等到本书读完以后再返回来理解。
queue.h

#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) {};//使用初始化列表来初始化const类
	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

#include "queue.h"
#include <cstdlib>

Queue::Queue(int qs):qsize(qs)//构造函数,元素(节点)数量默认值是Q_SIZE(10)
{
	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;//item为链表中第一个元素的内容
	items--;
	Node *temp=front;
	front=front->next;//第一个节点变为下一个节点
	delete temp;//把原来front中的内容删除
	if(items==0)
		rear=NULL;
	return true;
}

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

bank.cpp

#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 Healther Automatic Teller\n";
	cout << "Enter maxinum size of queue: ";
	int qs;
	cin >> qs;
	Queue line(qs); //创建节点数为qs的链表
	cout << "Enter the number of simulation hours: ";
	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++)//cyclelimit 是总模拟时间
	{
		if(newcustomer(min_per_cust))
		{
			if(line.isfull())
				turnaways++;//队列已满,拒绝加入队列,拒绝提供服务
			else
			{
				customers++;//队列中客户数
				temp.set(cycle);//temp是customer的对象//cycle 是到达时间,记录cycle作为到达时间,并且随机生成花费时间,并记录
				line.enqueue(temp);//加入新的节点
			}
		}
		if(wait_time<=0&&!line.isempty())//如果等待时间小于等于0(即前面没有客户在被处理),即不用再等待,而且等待队列不为空
			//此时客户可以接受服务
		{
			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 << "   customer served: " << served << endl;//ATM服务的客户总人数
		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 << "Done!\n";
	return 0;
}

bool newcustomer(double x)//更加混乱的模拟,如果出现新客户则返回true
{
	return (std::rand() *x / RAND_MAX<1);//平均x分钟可能就会出现一个新顾客
}

12.10.5(此题是我遇到第一个非常复杂的题,因此在此处使用大量注释)

queue.h

#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) {};//使用初始化列表来初始化const类
	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

#include "queue.h"
#include <cstdlib>

Queue::Queue(int qs):qsize(qs)//构造函数,元素(节点)数量默认值是Q_SIZE(10)
{
	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;//item为链表中第一个元素的内容
	items--;
	Node *temp=front;
	front=front->next;//第一个节点变为下一个节点
	delete temp;//把原来front中的内容删除
	if(items==0)
		rear=NULL;
	return true;
}

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

bank.cpp

#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 Healther Automatic Teller\n";
	cout << "Enter maxinum size of queue: ";
	int qs;
	cin >> qs;
	Queue line(qs); //创建节点数为qs的链表
	cout << "Enter the number of simulation hours: (>=100)";
	int hours;
	cin >> hours;
	long cyclelimit=MIN_PER_HR*hours;//总模拟时间分钟数
	double perhour=0.0;
	double average=0.0;
	while(average<=1)
	{
	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;//队列中累积的等待时间
	while(!line.isempty())
	{
		line.dequeue(temp);//清空原始链表,防止上次未接受服务的队列中的数据影响下一次模拟过程,非常关键
	}
	for(int cycle=0;cycle<cyclelimit;cycle++)//cyclelimit 是总模拟时间
	{
		if(newcustomer(min_per_cust))
		{
			if(line.isfull())
				turnaways++;//队列已满,拒绝加入队列,拒绝提供服务
			else
			{
				customers++;//出现在队列中客户数
				temp.set(cycle);//temp是customer的对象//cycle 是到达时间,记录cycle作为到达时间,并且随机生成花费时间,并记录
				line.enqueue(temp);//加入新的节点
			}
		}
		if(wait_time<=0&&!line.isempty())//如果等待时间小于等于0(即前面没有客户在被处理),即不用再等待,而且等待队列不为空
			//此时客户可以接受服务
		{
			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 << endl;
		cout << " customers perhour: " << perhour << endl;
		cout << "customers accepted: " << customers << endl;//加入过队列的客户总人数
		cout << "  customers served: " << served << endl;//ATM服务的客户总人数
		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";
		average=(double) line_wait/ served;
	}
	else
		cout << "Done!\n";
	}
	cout << "To aim to make wait time <=1 min, average of customers numbers should be " << perhour-1 << endl;
	return 0;
}

bool newcustomer(double x)//如果出现新客户则返回true
{
	return (std::rand() *x / RAND_MAX<1);//平均x分钟可能就会出现一个新顾客
}

12.10.6

queue.h

#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) {};//使用初始化列表来初始化const类
	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

#include "queue.h"
#include <cstdlib>

Queue::Queue(int qs):qsize(qs)//构造函数,元素(节点)数量默认值是Q_SIZE(10)
{
	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;//item为链表中第一个元素的内容
	items--;
	Node *temp=front;
	front=front->next;//第一个节点变为下一个节点
	delete temp;//把原来front中的内容删除
	if(items==0)
		rear=NULL;
	return true;
}

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

bank.cpp

#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 Healther Automatic Teller\n";
	cout << "Enter maxinum size of queue: ";
	int qs;
	cin >> qs;
	Queue line1(qs), line2(qs); //创建节点数为qs的两个链表
	cout << "Enter the number of simulation hours: (>=100)";
	int hours;
	cin >> hours;
	long cyclelimit=MIN_PER_HR*hours;//总模拟时间分钟数
	double perhour=0.0;
	double average=0.0;

	while(average<=1)
	{
	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_time1=0, wait_time2=0;//等待时间
	long line_wait=0;//队列中累积的等待时间
	while(!line1.isempty())
	{
		line1.dequeue(temp);//清空原始链表,防止上次未接受服务的队列中的数据影响下一次模拟过程,非常关键
	}
	while(!line2.isempty())
	{
		line2.dequeue(temp);
	}

	for(int cycle=0;cycle<cyclelimit;cycle++)//cyclelimit 是总模拟时间
	{
		if(newcustomer(min_per_cust))
		{
			if(line1.isfull() && line2.isfull())
				turnaways++;//队列已满,拒绝加入队列,拒绝提供服务
			else
			{
				customers++;//出现在队列中客户数
				temp.set(cycle);//temp是customer的对象//cycle 是到达时间,记录cycle作为到达时间,并且随机生成花费时间,并记录
				if(line1.queuecount() < line2.queuecount())
					line1.enqueue(temp);
				else
					line2.enqueue(temp);//加入新的节点
			}
		}

		if(wait_time1<=0&&!line1.isempty())//如果等待时间小于等于0(即前面没有客户在被处理),即不用再等待,而且等待队列不为空
			//此时客户可以接受服务
		{
			line1.dequeue(temp);//出队
			wait_time1=temp.ptime();//等待时间等于处理时间//新用户的所需的处理时间
			line_wait+=(cycle-temp.when());//排队等待的总时间
			served++;//服务人数
		}
		if(wait_time1>0)
			wait_time1--;//客户处理中
		sum_line+=line1.queuecount();

		if(wait_time2<=0&&!line2.isempty())//如果等待时间小于等于0(即前面没有客户在被处理),即不用再等待,而且等待队列不为空
			//此时客户可以接受服务
		{
			line2.dequeue(temp);//出队
			wait_time2=temp.ptime();//等待时间等于处理时间//新用户的所需的处理时间
			line_wait+=(cycle-temp.when());//排队等待的总时间
			served++;//服务人数
		}
		if(wait_time1>0)
			wait_time1--;//客户处理中
		sum_line+=line2.queuecount();
	}

	if(customers>0)
	{
		cout << endl;
		cout << " customers perhour: " << perhour << endl;
		cout << "customers accepted: " << customers << endl;//加入过队列的客户总人数
		cout << "  customers served: " << served << endl;//ATM服务的客户总人数
		cout << "         turnaways: " << turnaways << endl;
		cout << "average queue size: ";//平均队列长度
		cout.precision(2);
		cout.setf(ios_base::fixed, ios_base::floatfield);
		cout << (double) sum_line/(cyclelimit*2)<< endl;
		cout << " average wait time: "//平均等待时间
			<< (double) line_wait/ served << "minutes\n";
		average=(double) line_wait/ served;
	}
	else
		cout << "Done!\n";
	}
	cout << "To aim to make wait time <=1 min, average of customers numbers should be " << perhour-1 << endl;
	return 0;
}

bool newcustomer(double x)//如果出现新客户则返回true
{
	return (std::rand() *x / RAND_MAX<1);//平均x分钟可能就会出现一个新顾客
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值