#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
template<class T>
struct quenode{
T nodedata;
quenode*next;
};
template<class T>
class queue{
protected:
int quesize;
quenode<T>*head;
quenode<T>*tail;
bool allocateerror;
queue ©(queue &q);
public:
queue();
queue(queue &q)
{
head=NULL;tail=NULL;copy(q);
}
~queue()
{
clearque();
}
bool getallocateerror()
{
return allocateerror;
}
void push(T &);
bool pop(T &);
bool isempty()
{
return (quesize==0)?true:false;
}
void clearque();
queue&operator=(queue &q)
{
copy(q);
return *this;
}
};
template<class T>
queue<T>::queue()
{
quesize=0;
allocateerror=false;
head=NULL;
tail=NULL;
}
template<class T>
queue<T>& queue<T>::copy(queue<T>&que) //将队列que复制给当前队列对象
{
quenode<T> *p,*q,*r;
if(head)clearque();
quesize=que.quesize;
allocateerror=false;
head=NULL;
tail=NULL;
if(!que.head)
return *this; //对象为空则返回
head=new quenode<T>;
if(!head)
{
allocateerror=true;
return *this;
}
head->nodedata=que.head->nodedata;
head->next=NULL;
tail=head;
r=NULL;
p=head;
q=que.head->next;
while(q) //循环进行后续节点的赋值
{
r=new quenode<T>;
if(!r)
{
allocateerror=true;
return *this;
}
r->nodedata=q->nodedata;
r->next=NULL;
p->next=r; //将节点链接到当前队列的链上
tail=r;
p=p->next; //指针后移
q=q->next;
}
return *this;
}
template<class T>
void queue<T>::push(T &x)
{
quenode<T>*p;
p=new quenode<T>;
if(!p)
{
allocateerror=true;
return;
}
p->nodedata=x;
if(tail)
{
p->next=NULL;
tail->next=p;
tail=p;
}
else{
p->next=NULL;
tail=p;
head=p;
}
quesize++;
}
template<class T>
bool queue<T>::pop(T &x)
{
quenode<T>*p;
if(head)
{
x=head->nodedata;
p=head;
head=head->next; //修改队头指针
if(head==NULL)
tail=NULL;
delete p;
quesize--;
return true;
}
return false;
}
template<class T>
void queue<T>::clearque()
{
T p;
allocateerror=false;
while (pop(p));
head=tail=NULL;
}
class staff{ //职工类
private:
string name;
int age;
float salary;
string sex;
public:
void assign(string name,int age,float salary,string sex)
{
staff::name=name;
staff::age=age;
staff::salary=salary;
staff::sex=sex;
}
void print()
{
cout<<name;
printf("%6d%10.2f",age,salary); //printf只能输出C语言内置的数据,而string不是内置的
cout<<setw(8)<<sex<<endl;
}
};
void viewque(queue<staff>&que)
{
int i=1;
staff p;
queue<staff>quecopy(que);
system("cls");
while(quecopy.pop(p))
{
printf("%2d:",i++);
p.print();
}
}
int main()
{
queue<staff>que;
staff p;
p.assign("小明",20,1500,"男");
que.push(p);
p.assign("二明",21,3000,"女");
que.push(p);
p.assign("三明",22,4000,"男");
que.push(p);
p.assign("四明",23,5000,"女");
que.push(p);
viewque(que);
return 0;
}
队列类模板的使用
最新推荐文章于 2022-07-15 17:40:22 发布