C++ Primer Plus(第6版)---编程作业完成(第十二章)

charpter12_homework.cpp

#include<iostream>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include"String2.h"
#include"stock.h"
#include"stack1.h"
#include"queue.h"

using namespace std;
void p12_1(void);
void p12_2(void);
void p12_3(void);
void p12_4(void);
void p12_5(void);
void p12_6(void);
int main()
{
	//p12_1();
	//p12_2();
	//p12_3();
	//p12_4();
	//p12_5();
	p12_6();
	return 0;
}

//---------------作业一------------
class Cow
{
private:
	char name[20];
	char* hooby;
	double weight;
public:
	Cow(){name[0]='\0';hooby=nullptr;weight=0.0;};//默认构造
	Cow(const char* nm,const char* ho,double wt);
	Cow(const Cow& c);//复制构造,深度复制
	~Cow(){delete [] hooby;};
	Cow& operator=(const Cow& c);
	void ShowCow()const;
};
//自定义构造函数
Cow::Cow(const char* nm,const char* ho,double wt)
{
	/*for(i=0;i<20 && nm[i]!='\0';i++)
		name[i]=nm[i];
	name[i]*/
	strcpy(name,nm);
	hooby=new char[strlen(ho)+1];
	strcpy(hooby,ho);
	weight=wt;
}
//复制构造函数
Cow::Cow(const Cow& c)//复制构造,深度复制
{
	strcpy(name,c.name);
	hooby=new char[strlen(c.hooby)+1];
	strcpy(hooby,c.hooby);
	weight=c.weight;
}
//=赋值重载运算符
Cow& Cow::operator=(const Cow& c)
{
	strcpy(name,c.name);
	hooby=new char[strlen(c.hooby)+1];
	strcpy(hooby,c.hooby);
	weight=c.weight;
	return *this;//!!!
}
//展示函数
void Cow::ShowCow()const
{
	cout<<"name: ";
	for(int i=0;i<20 && name[i]!='\0';i++)
		cout<<name[i];
	cout<<endl;
	cout<<"hobby: "<<hooby<<endl;
	cout<<"weight: "<<weight<<endl;
}
void p12_1(void)
{
	Cow c1;
	char arr[20]="Maomao";
	Cow c2(arr,"C++",12.0);
	c2.ShowCow();
	Cow c3=c2;//复制构造函数
	c3.ShowCow();
	c1=c3;
	c1.ShowCow();
}

//-----------作业二-------------
void p12_2(void)
{
	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<<"\n contains "<<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";
	return;
}

//------------作业三--------------
void p12_3(void)
{
	const int STKS=4;
	//创建对象数组,必须有默认构造函数
	Stock stocks[STKS]={
	Stock("NanoSmart",12,20.0),
	Stock(),
	Stock("Monolistic Obelisks",130,3.25)
	//没有初始化的值自动调用默认构造函数
	};
	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<<"max: "<<endl;
	cout<<(*top);
	return;
}


//-----------作业四----------
void p12_4(void)
{
	 Stack s1;
	 unsigned long po;
	 s1.push(123);
	 s1.push(456);
	 s1.push(789);
	 s1.pop(po);
	 cout<<"s1 pop: "<<po<<endl;//789
	 Stack s2(s1);
	 s2.pop(po);
	 cout<<"s2 pop: "<<po<<endl;//456
	 Stack s3;
	 s3=s2;
	 s3.pop(po);
	 cout<<"s3 pop: "<<po<<endl;//123
}


//----------作业五---------
//判断用户是否来了
bool newcustomer(double x)
{
	return (std::rand()*x/RAND_MAX<1);
}

void p12_5(void)
{
	const int MIN_PER_HR=60;
	Item temp;
	 long turnaways;
	 long customers;
	 long served;
	 long sum_line;
	 int wait_time;
	 long line_wait;
	 double aveg_wait;
	 //设置仿真时间
	int hours=100;
	long cyclelimit=MIN_PER_HR*hours;
	//设置客流量15递增
	double perhour=20;
	double min_per_cust;
	min_per_cust=MIN_PER_HR/perhour;
	srand(time(0));//随机初始化rand(),随机设置随机数种子
	//输入队列最大长度
	cout<<"Enter the maximum size of queue: ";
	int qs;
	cin>>qs;
	Queue line(qs);
	
	do{
		turnaways=0;
		 customers=0;
		 served=0;
		 sum_line=0;
		 wait_time=0;
		 line_wait=0;
		 aveg_wait=0.0;

		//清空队列
		while(!line.isempty())
			line.dequeue(temp);

		 //大循环计时
		 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.deq_count();//每分钟的队列数相加,之后除以总分钟,得到平均队列长度
		 }
		 if(customers>0)
		 {
			 cout<<"customers= "<<customers<<endl;
			 cout<<"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;
			 aveg_wait=(double)line_wait/served;
			 cout<<"average wait time: "<<aveg_wait<<endl;
			 cout<<"perhour: "<<perhour<<endl;
		 }
		 else
			 cout<<"No customers!\n";
		 if(aveg_wait <=0.9)
			 perhour++;
		 else if(aveg_wait>=1.1)
			 perhour--;
		 else ;
	}while (aveg_wait <=0.9 || aveg_wait>=1.1);
	cout<<"Done!\n";
	return;
}


//-----------作业六-----------
void p12_6(void)
{
	const int MIN_PER_HR=60;
	Item temp;
	 long turnaways;
	 long customers;
	 long served;
	 long sum_line;
	 int wait_time1;
	 int wait_time2;
	 long line_wait;
	 double aveg_wait;
	 //设置仿真时间
	int hours=100;
	long cyclelimit=MIN_PER_HR*hours;
	//设置客流量
	double perhour=50;
	double min_per_cust;
	min_per_cust=MIN_PER_HR/perhour;
	
	//输入队列最大长度
	cout<<"Enter the maximum size of queue: ";
	int qs;
	cin>>qs;
	Queue line_1(qs);
	Queue line_2(qs);
	
	do{
		srand(time(0));//随机初始化rand(),随机设置随机数种子
		turnaways=0;
		customers=0;
		served=0;
		sum_line=0;
		wait_time1=0;
		wait_time2=0;
		line_wait=0;
		aveg_wait=0.0;

		//清空队列
		while(!line_1.isempty())
			line_1.dequeue(temp);
		while(!line_2.isempty())
			line_2.dequeue(temp);

		 //大循环计时
		 for(int cycle=0;cycle<cyclelimit;cycle++)
		 {
			 if(newcustomer(min_per_cust))
			 {
				 if(line_1.isfull() && line_2.isfull())
					 turnaways++;
				 else if(line_1.deq_count()>line_2.deq_count())
				 {
					 customers++;
					 temp.set(cycle);
					 line_2.enqueue(temp);
				 }
				 else
				 {
					 customers++;
					 temp.set(cycle);
					 line_1.enqueue(temp);
				 }
			 }
			 if(wait_time1<=0 && !line_1.isempty())//已处理且队列有人
			 {
				 line_1.dequeue(temp);//删除队列,开始处理
				 wait_time1=temp.ptime();//获取此顾客的处理时间
				 line_wait+=cycle-temp.when();//获取顾客等待时间,并相加所有
				 served++;
			 }
			 if(wait_time2<=0 && !line_2.isempty())//已处理且队列有人
			 {
				 line_2.dequeue(temp);//删除队列,开始处理
				 wait_time2=temp.ptime();//获取此顾客的处理时间
				 line_wait+=cycle-temp.when();//获取顾客等待时间,并相加所有
				 served++;
			 }
			 if(wait_time1>0)//正在处理中
				 wait_time1--;
			 if(wait_time2>0)//正在处理中
				 wait_time2--;
			 sum_line+=line_1.deq_count();//每分钟的队列数相加,之后除以总分钟,得到平均队列长度
			 sum_line+=line_2.deq_count();
		 }
		 if(customers>0)
		 {
			 cout<<"customers= "<<customers<<endl;
			 cout<<"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;
			 aveg_wait=(double)line_wait/served;
			 cout<<"average wait time: "<<aveg_wait<<endl;
			 cout<<"perhour: "<<perhour<<endl;
		 }
		 else
			 cout<<"No customers!\n";
		 if(aveg_wait <=0.9)
			 perhour++;
		 else if(aveg_wait>=1.1)
			 perhour--;
		 else ;
	}while (aveg_wait <=0.9 || aveg_wait>=1.1);
	cout<<"Done!\n";
}

String2.h

#ifndef STRING1_H_
#define STRING1_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();//默认构造函数
	String(const char* s);
	String(const String& s);//复制构造函数
	~String();//析构函数
	int length()const {return len;};
	//重载“=”
	String& operator=(const String& s);
	String& operator=(const char* s);//为了不调用构造函数创造临时对象,提高效率

	String operator+(const String& s);
	String operator+(const char* s);//返回临时变量

	//变小写成员函数
	String& Stringlow();
	//变大写成员函数
	String& Stringup();

	//查询字符数量
	int has(char ch);

	//重载“[]”,之能在成员函数中重载
	char& operator[](int i);
	const char& operator[](int i)const;

	//重载关系运算符,友元函数,方便与常规C字符串进行比较
	friend bool operator<(const String& s1,const String& s2);
	friend bool operator>(const String& s1,const String& s2);
	friend bool operator==(const String& s1,const String& s2);

	//重载"+"号运算符
	friend String operator+(const char* s1,String& s2);

	//重载输入输出,友元函数
	friend ostream& operator<<(ostream& os,String& s);
	friend istream& operator>>(istream& is,String& s);
	
	//静态类成员函数
	static int HowMany();
};

#endif

String2.cpp

#include<iostream>
#include<cstring>
#include<cctype>
#include"String2.h"
using std::cout;
using std::endl;

//初始化静态成员
int String::num_strings=0;
//静态类成员函数
int String::HowMany()
{
	return num_strings;
}

String::String()//默认构造函数
{
	len=4;
	str=new char[1];
	str[0]='\0';
	num_strings++;
}
String::String(const char* s)
{
	len=strlen(s);
	str=new char[len+1];
	strcpy(str,s);
	num_strings++;
}
String::String(const String& s)//复制构造函数
{
	//深度拷贝
	len=s.len;
	str=new char[len+1];
	strcpy(str,s.str);
	num_strings++;//所有对象共享一份
}
String::~String()//析构函数
{
	--num_strings;
	delete []str;
}

//重载“=”
String& String::operator=(const String& s)//深度拷贝
{
	//首先预防自己拷贝自己,因为会先释放掉原有空间
	if(this==&s)//检查地址是否为同一块内存
		return *this;
	//释放原有空间
	delete []str;
	len=s.len;
	str=new char[len+1];
	strcpy(str,s.str);
	return *this;
}
String& String::operator=(const char* s)
{
	//释放原有内存
	delete []str;
	len=strlen(s);
	str=new char[len+1];
	strcpy(str,s);
	return *this;
}
//重载“[]”,只能在成员函数中重载
char& String::operator[](int i)
{
	return str[i];
}
const char& String::operator[](int i)const
{
	return str[i];
}

//重载关系运算符,友元函数,方便与常规C字符串进行比较
bool operator<(const String& s1,const String& s2)
{
	return (strcmp(s1.str,s2.str)<0);
}
bool operator>(const String& s1,const String& s2)
{
	return s2<s1;
}
bool operator==(const String& s1,const String& s2)
{
	return(strcmp(s1.str,s2.str)==0);
}
//重载输入输出,友元函数
ostream& operator<<(ostream& os,String& s)
{
	os<<s.str;
	return os;
}
istream& operator>>(istream& is,String& s)
{
	char temp[String::CINLIM];
	is.get(temp,String::CINLIM);
	if(is)
		s=temp;
	while(is && is.get()!='\n')
		continue;
	return is;

}

//重载"+",成员函数
String String::operator+(const String& s)
{
	String temp;
	temp.len=len+s.len;
	temp.str=new char[temp.len+1];
	strcpy(temp.str,str);
	strcpy(temp.str+len,s.str);
	temp.str[temp.len]='\0';
	return temp;
}
String String::operator+(const char* s)
{
	String temp;
	temp.len=len+strlen(s);
	temp.str=new char[temp.len+1];
	strcpy(temp.str,str);
	strcpy(temp.str+len,s);
	temp.str[temp.len]='\0';
	return temp;
}

//重载"+"号运算符
String operator+(const char* s1,String& s2)
{
	String temp;
	temp.len=s2.len+strlen(s1);
	temp.str=new char[temp.len+1];
	strcpy(temp.str,s1);
	strcpy(temp.str+strlen(s1),s2.str);
	temp.str[temp.len]='\0';
	return temp;
}

//变小写成员函数
String& String::Stringlow()
{
	for(int i=0;str[i]!='\0';i++)
		str[i]=tolower(str[i]);
	return *this;
}
//变大写成员函数
String& String::Stringup()
{
	for(int i=0;str[i]!='\0';i++)
		str[i]=toupper(str[i]);
	return *this;
}
//查询字符数量
int String::has(char ch)
{
	int num=0;
	for(int i=0;str[i]!='\0';i++)
	{
		if(str[i]==ch)
			num++;
	}
	return num;
}

stock.h

#ifndef STOCK_H_
#define STOCK_H_
#include<iostream>
using std::ostream;
class Stock
{
	//默认为Private
private://数据隐藏
	char* company;//char* 指针
	long shares;
	double share_val;
	double total_val;
	void set_total(){total_val=shares*share_val;};
public://公共接口
	//默认构造函数
	Stock();
	//构造函数
	Stock(const char* s,long n,double pr);
	//析构函数
	~Stock();
	void buy(long num,double price);
	void sell(long num,double price);
	void update(double price);
	//void show()const;//此处const限定不修改
	//增加this指针,比较两个类对象较大值,返回
	const Stock& topval(const Stock& s)const;
	//友元函数,重载<<
	friend ostream& operator<<(ostream& os,const Stock& s);

};

#endif

stock.cpp

#include<iostream>
#include<cstring>
#include"stock.h"
using namespace std;
//类成员函数定义
//默认构造函数
Stock::Stock()
{
	cout<<"Default constructor called."<<endl;
	company=new char[4];
	strcpy(company,"C++");
	shares=0;
	share_val=0.0;
	total_val=0.0;
}
//构造函数没有返回值,构造函数形参名称不要与数据成员相同
Stock::Stock(const char* s,long n,double pr)
{
	company=new char[strlen(s)+1];
	strcpy(company,s);
	if (n<0)
	{
		cout<<"Number of shares can't be negative!"
			<<company<<" shares is set to be 1.\n";
		shares=0;
	}
	else
		shares=n;
	share_val=pr;
	set_total();
}
//析构函数
Stock::~Stock()
{
	cout<<"Bye"<<company<<endl;
	delete [] company;
}
void Stock::buy(long num,double price)
{
	if (num<0)
		cout<<"Number of shares can't be negative!\n";
	else
	{
		shares+=num;
		share_val=price;
		set_total();
	}
}
void Stock::sell(long num,double price)
{
	if (num<0)
		cout<<"Number of shares can't be negative!\n";
	else if(num>shares)
		cout<<"You don't have these number!\n";
	else
	{
		shares-=num;
		share_val=price;
		set_total();
	}
}
void Stock::update(double price)
{
	share_val=price;
}

定点显示法
//void Stock::show()const
//{
//	//#.###
//	ios_base::fmtflags orig=cout.setf(ios_base::fixed,ios_base::floatfield);
//	std::streamsize prec=cout.precision(3);
//	cout<<"Company: "<<company<<"Shares: "<<shares<<endl;
//	//#.##
//	cout.precision(2);
//	cout<<"Total Worth: $"<<total_val<<endl;
//	//还原
//	cout.setf(orig,ios_base::floatfield);
//	cout.precision(prec);
//}

//增加this指针,比较两个类对象较大值,返回
//this指针指向调用对象
const Stock& Stock::topval(const Stock& s)const
{
	if(total_val<s.total_val)
		return s;
	else
		return *this;
}

//友元函数,重载<<
ostream& operator<<(ostream& os,const Stock& s)
{
	//#.###
	ios_base::fmtflags orig=os.setf(ios_base::fixed,ios_base::floatfield);
	std::streamsize prec=os.precision(3);
	os<<"Company: "<<s.company<<"Shares: "<<s.shares;
	//#.##
	os.precision(2);
	os<<"Total Worth: $"<<s.total_val<<endl;
	//还原
	os.setf(orig,ios_base::floatfield);
	os.precision(prec);
	return os;//!!!
}

stack1.h

#ifndef STACK1_H_
#define STACK1_H_

typedef unsigned long Item1;
class Stack
{
private:
	enum {MAX=10};
	Item1* pitems;
	int size;
	int top;
public:
	Stack(int n=MAX);//默认参数相当于默认构造
	Stack(const Stack& st);//复制构造
	~Stack();
	bool isempty()const;
	bool isfull()const;
	bool push(const Item1& item);
	bool pop(Item1& item);
	Stack& operator=(const Stack& st);
};

#endif

stack1.cpp

#include<iostream>
#include"stack1.h"
using namespace std;

Stack::Stack(int n)//默认参数相当于默认构造,创建n个元素的栈
{
	pitems=new Item1[n];
	size=n;//n是栈的大小容量
	top=0;
}
Stack::Stack(const Stack& st)//复制构造,深度复制
{
	size=st.size;
	top=st.top;
	pitems=new Item1[size];
	for(int i=0;i<top;i++)
		pitems[i]=st.pitems[i];
}
Stack::~Stack()//析构函数
{
	delete [] pitems;
}
bool Stack::isempty()const
{
	if(top==0)
		return true;
	else
		false;
}
bool Stack::isfull()const
{
	if(top==size)
		return true;
	else
		return false;
}
bool Stack::push(const Item1& item)
{
	//检查栈是否为满
	if(top<size)
	{
		pitems[top++]=item;
		return true;
	}
	else
	{
		cout<<"FULL\n";
		return false;
	}

}
bool Stack::pop(Item1& item)
{
	//检查栈是否空
	if(top==0)
	{
		cout<<"Empty\n";
		return false;
	}
	else
	{
		item=pitems[--top];
		return true;
	}
}
Stack& Stack::operator=(const Stack& st)//深度复制
{
	//检查是否是自己
	if(this==&st)//地址是否为同一块内存
		return *this;
	else
	{
		//删除自己
		delete [] pitems;
		size=st.size;
		top=st.top;
		pitems=new Item1[size];
		for(int i=0;i<top;i++)
		pitems[i]=st.pitems[i];
	}
	return *this;
}

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:
	enum {Q_SIZE=10};//符号常量
	struct Node{Item item;struct Node * next;};//结点结构体
	Node* front;//头指针
	Node* rear;//尾指针
	int num;
	const int q_size;
public://公共接口
	Queue(int q_size=Q_SIZE);//默认参数
	~Queue();
	bool isfull()const{return (num==q_size);};
	bool isempty()const{return (num==0);};
	bool enqueue(const Item& item);
	bool dequeue(Item& item);
	int deq_count()const{return num;};
};
#endif

queue.cpp

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

Queue::Queue(int qs):q_size(qs)
{
	front=rear=nullptr;
	num=0;
}
Queue::~Queue()//要析构掉队列所有结点及其指向的空间
{
	Node* temp;
	while(front!=nullptr)
	{
		temp=front;
		front=front->next;
		delete temp;
	}
}
bool Queue::enqueue(const Item& item)
{
	//判断满没有
	if(isfull())
		return false;
	//增加新节点
	Node* add=new Node;
	//设置新指针
	add->item=item;
	add->next=nullptr;
	num++;
	//进行连接
	if(front==nullptr)//如果是空指针,还要设置头指针
		front=add;
	else
		rear->next=add;
	rear=add;
	return true;
}
bool Queue::dequeue(Item& item)
{
	//判断空没有
	if(isempty())
		return false;
	//转移数据
	item=front->item;
	num--;
	删除头指针指向的空间
	Node* temp=front;
	front=front->next;
	delete temp;
	//判断是否为空
	if(num==0)
		rear=nullptr;
	return true;
}
void Customer::set(long when)
{
	processtime=std::rand()%3+1;
	arrive=when;
}

如有错误,欢迎指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值