版本比较
手写queue
正文
增加 26 行删除 26 行
9 行未改动10111213141415161717181920212222232425262727282930313232333435362 行未改动39404142434344454647484950515253535455565758575859606161626364646566676768697071717273747475767778798081818283848485868788899091919293949596979898991001011023 行未改动1061071081091101101111121131141141151161171182 行未改动1211221231241251251261271281281291301311311321331341351361371371381391401391401411421431448 行未改动9 行未改动using namespace std;template<class T>class vector{ public: T* p=NULL;//数组的首指针 T* p=NULL;//数组的首指针 int tot; //数组的长度 int siz;//数组的容量 vector(int b){//初始化一个长度为b的数组 vector(int b){//初始化一个长度为b的数组 this->siz=b; this->tot=0; p=(T*)malloc(b*sizeof(T)); } vector(){//初始化一个长度为1的数组 vector(){//初始化一个长度为1的数组 this->siz=1; this->tot=0; p=(T*)malloc(sizeof(T)); } T* reserve(int len){//将数组容量改为len T* reserve(int len){//将数组容量改为len this->siz=len; p=(T*)realloc(p,len*sizeof(T)); return p; } void swap(vector a,vector b){//交换两个数组,时间复杂度为O(1) void swap(vector a,vector b){//交换两个数组,时间复杂度为O(1) T* p1=a.p; a.p=b.p; b.p=p1; int tot1=a.tot;2 行未改动 int size1=a.siz; a.siz=b.siz; b.siz=size1; } T at(int i){//访问下标为i的元素,若越界则输出Error T at(int i){//访问下标为i的元素,若越界则输出Error if(i>=this->tot){ cerr<<"Error"<<'\n'; exit(0); } return *(p+i); } T operator [](int i){//访问下标为i的元素 return *(p+i); } T operator =(vector<T> a){//赋值,时间复杂度为O(1) T operator =(vector<T> a){//赋值,时间复杂度为O(1) this->p=(T*)realloc(a.p,a.siz*sizeof(T)); this->siz=a.siz; this->tot=a.tot; } int size(){//返回数组容量 } int size(){//返回数组容量 return this->siz; } int length(){//返回数组长度 int length(){//返回数组长度 return this->tot; } bool empty(){//判断数组是否为空 bool empty(){//判断数组是否为空 return tot==0; } T front(){//返回数组的首个元素 T front(){//返回数组的首个元素 if(empty()){ cerr<<"Error"<<'\n'; exit(0); } } return *p; } T back(){//返回数组最后的元素 T back(){//返回数组最后的元素 if(empty()){ cerr<<"Error"<<'\n'; exit(0); } return *(p+tot-1); } T* data(){//返回数组的首指针 T* data(){//返回数组的首指针 return p; } void push_back(T x){//往数组末尾添加一个元素 void push_back(T x){//往数组末尾添加一个元素 if(tot==siz){ this->reserve(siz*2); } ++(this->tot); *(p+tot-1)=x; } void pop_back(){//将数组末尾的元素弹出 void pop_back(){//将数组末尾的元素弹出 if(empty()){ cerr<<"Error"<<'\n'; exit(0); } --(this->tot); } void clear(){//清空数组 void clear(){//清空数组 for(int* i=p;i!=p+tot-1;++i){ (*i)=0; } tot=0;3 行未改动class queue{ public: int head,fail; vector<T> q; queue(){//初始化队列 queue(){//初始化队列 head=0; fail=0; } void push(T x){//往队尾加入一个元素 void push(T x){//往队尾加入一个元素 q.push_back(x); ++fail; } T front(){//访问队首2 行未改动 exit(0); } return *(q.p+head); } int size(){//返回元素个数 int size(){//返回元素个数 return fail-head; } bool empty(){//返回是否为空 bool empty(){//返回是否为空 return head==fail; } void pop(){//在队首弹出一个元素 void pop(){//在队首弹出一个元素 if(empty()){ cerr<<"Error"<<'\n'; exit(0); } ++head; } }};queue<int> q; int main(){ queue<int> q;int main(){ q.push(114514); q.push(1919810); cout<<q.front()<<' '<<'\n'; q.pop();8 行未改动