写一个队列标准库模板
一、代码
#include <iostream>
using namespace std;
template <typename T>
class my
{
private:
T* first;
T* last;
T* end;
T temp;
public:
//构造函数
my(int size=2)
{
first=new T[size];
last=first;
end=first+size;
}
//析构函数
~my()
{
delete []first;
first=last=end=nullptr;
}
//拷贝构造函数
my(const my &Q)
{
//实际占用大小
int len=Q.last-Q.first;
//空间大小
int size=Q.end-Q.first;
//建立新对象的容量
this->first=new T[size];
//拷贝
memcpy(this->first,Q.first,len*sizeof(T));
//另外两个指针的指向明确
this->last=this->first+len;
this->end=this->first+size;
}
//判空
int empty()
{
return this->first == this->last;
}
//判满
int full()
{
return this->last == this->end;
}
//扩容原则:2倍扩容
void add()
{
//获取之前容量
int size=this->end-this->first;
//申请二倍空间
T* temp=new T[2*size];
//拷贝原来数值
memcpy(temp,this->first,size*sizeof(T));
delete []first;
this->first=temp;
this->end=this->first+2*size;
this->last=this->first+size;
}
//队列尾插
void put_my(const T val)
{
//判断队列是否满了
if(this->full())
{
this->add();
}
*last=val;
last++;
}
//队列头删除
void post_my()
{
if(this->empty())
{
cout<<"队列为空"<<endl;
return;
}
for(int i=1;i<this->len();i++)
{
first[i-1]=first[i];
}
--last;
}
//空间大小
int size()
{
return end-first;
}
//实际使用大小
int len()
{
return last-first;
}
//返回当前元素的引用
T &at(int index)
{
if(index<0 || index>this->len())
{
cout<<"访问越界"<<endl;
}
return first[index];
}
};
int main()
{
my<int> v1;
cout<<"循环输入十个数"<<endl;
for(int i=0;i<10;i++)
{
v1.put_my(i);
}
for(int i=0;i<v1.len();i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
cout<<"队列删除一个元素"<<endl;
v1.post_my();
for(int i=0;i<v1.len();i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
cout<<"队列插入一个元素"<<endl;
v1.put_my(10);
for(int i=0;i<v1.len();i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
return 0;
}
二、执行结果