循环队列类模板和函数模板c++实例

/*此程序是使用函数模板和类模板的一个例子:函数模板为求出数组的前n项和,类模板为一个循环队列类模板*/
#include<iostream>
using namespace std;
template<class T>T Total(T, int);/*函数模板*/
/*循环队列类模板规则:
1、当首和尾相同时代表队列为空,即front=real;
2、往队尾添数据时real在添完后+1,从队首删除数据时front在删完后+1,
故当(real - front == Maxsize - 1) || front - real == 1时代表队列已满(空出一位来区分队列满和空,size为循环队列的大小)*/
//此规则为个人定义,不同者大同小异
template<class K>class Queue{/*队列类模板*/
int Maxsize, front, real;//代表队列的大小,首和尾
K * queue;
public:
Queue(int size){//size为使用时用户输入的循环队列的大小
Maxsize = size;
queue = new K[Maxsize];
real = front = 0;//预设时数组为空
}
bool isEmpty(){//判断队列是否为空
if (real == front)
return true;//队列已空
return false;
}
bool isFull(){//判断队列是否是满
if ((real - front == Maxsize - 1) || front - real == 1)
return true;//队列已满
return false;
}
void Add(K);//往队尾添数据
K Delete();//从队首删数据
~Queue(){
delete[]queue;
}
};
//函数成员在体外定义要在函数名前加上限定符,“Queue<K> ”
template<class K>void Queue<K>::Add(K elem){//往队尾添数据
if (isFull()){//如果队列已满则退出
cout << " the queue is full! " << endl;
return;
}
queue[real] = elem;
real = (real + 1) % Maxsize;
return;
}
template<class K>K Queue<K>::Delete(){//从队首删数据
if (isEmpty()){
cout << " the queue is empty!" << endl;
exit(0);//表示正常终止进程,若参数不为0则表示异常终止
}
K res = queue[front];
front = (front + 1) % Maxsize;
return res;
}
///函数模板原型说明
template<class T>T Total(T a[], int size){
T total = a[0];
for (int i = 1; i < size; i++)
total = a[i] + total;
return total;
};
主函数
int main(){
int i = 0, a[20];
Queue<int> q1(10);//创建一个模板例子
while (!q1.isFull()){
q1.Add(i++);
a[i - 1] = i;
}
while (!q1.isEmpty())
cout << q1.Delete() << " ";
cout << endl;
int tt = Total(a, 5);//创建一个函数例子
cout << "the total of 5 numbers ==" << tt << endl;
return 0;
}

 

执行结果:

 

转载于:https://www.cnblogs.com/1996313xjf/p/5804947.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值