#include <iostream>
#include <queue>
using namespace std;
template <typename T>
class myQueue
{
private:
T *first;
T *last;
T *end;
public:
//构造函数
myQueue(int size = 1)
{
first = new T[size];
last = first; //为空
end = first+size; //空间尾指针
}
//析构函数
~myQueue()
{
delete [] first;
first = last = end = NULL;
}
//拷贝构造
myQueue(const myQueue &other)
{
//计算原空间大小
int len = other.last - other.first;
int size = other.end - other.first;
this->first = new T[size];//新对象容量
memcpy(this->first,other.first,len*sizeof(T));
//将该对象的另外两个指针指向对应位置
this->last = this->first+len;
this->end = this->first+size;
}
//判空
bool empty()
{
return this->first == this->last;
}
//判满
bool full()
{
return this->last == this->end;
}
//+1扩容
void greater()
{
//获取当前容器总容量
int size = this->end-this->first;
//在堆区申请二倍空间
T *temp = new T[size+1];
memcpy(temp,this->first,size*sizeof(T));
delete []first;
//更新指针指向
first = temp;
//更新其他指针指向
last = first+size;
end = first+size+1;
}
//入队
void push(const T val)
{
//判满
if(this->full())
{
this->greater(); //满了+1扩容
}
*last = val;
last++;
}
//出队
void pop()
{
if(this->empty())
{
return;
}
//尾指针
//获取当前容器总容量
int size = this->end-this->first;
//在堆区申请-1空间
T *temp = new T[size-1];
memcpy(temp,this->first+1,size*sizeof(T));
delete []first;
//更新指针指向
first = temp;
//更新其他指针指向
last = first+size-1;
end = first+size;
}
//实现获取对头
T front()const
{
return *first;
}
//实现获取对尾
T back()const
{
return *(last-1);
}
//计算元素个数
int size()
{
return last-first;
}
};
int main()
{
//定于新的栈s1
myQueue<int> q1;
//判空
cout<<"判空:"<<(q1.empty()?"yes":"no")<<endl;
//元素个数
cout<<"元素个数:"<<q1.size()<<endl;
//入队
for(int i=0;i<10;i++)
{
q1.push(i);
}
//元素个数
cout<<"元素个数:"<<q1.size()<<endl;
//访问第一个元素 对头
cout<<"队列头元素:"<<q1.front()<<endl;
//出列
q1.pop();
//访问第一个元素 对头
cout<<"队列头元素:"<<q1.front()<<endl;
//访问最后一个元素 队尾
cout<<"队列尾元素:"<<q1.back()<<endl;
}
判空:yes
元素个数:0
元素个数:10
队列头元素:0
队列头元素:1
队列尾元素:9