#include <iostream>
using namespace std;
template <typename T>
class MyVector
{
private:
T *first;
T *last; //最后一位数的下一位坐标
T *end; //整个容器的最后的下一位
public:
//无参构造
//MyVector():first(nullptr),last(nullptr),end(nullptr){}
//有参构造
MyVector(int size=2)
{
first=new T[size];
last=first;
end=first+size;
}
~MyVector()
{
delete []first;
cout<<"析构函数"<<endl;
}
//拷贝构造函数
MyVector(const MyVector &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->end;
}
//判满
bool full()
{
return this->last==this->end;
}
//扩容 初始size=2,所以2倍扩容
void greater()
{
int size=this->end-this->first;
T *newfirst=new T[size*2];
memcpy(newfirst,this->first,sizeof(T)*(size));
delete []first;
first=newfirst;
last=newfirst+size;
end=newfirst+size*2;
}
//尾插
void push_back(const T val)
{
if(full())
{
greater();
}
*(last)=val;
last++;
}
//尾删
void del_back()
{
if(empty())
{
cout<<"表已空,无法删除"<<endl;
return;
}
last--;
}
//头插
void push_head(const T val)
{
if(full())
{
greater();
}
T *now=this->last;
for(int i=0;i<this->last-this->first;i++)
{
*now=*(now-1);
now--;
}
*first=val;
last++;
}
//头删
void del_head()
{
if(empty())
{
cout<<"表已空,无法删除"<<endl;
return;
}
T *now=first;
for(int i=0;i<(this->last-this->first-1);i++)
{
*now=*(now+1);
now++;
}
last--;
}
void show()
{
int len=last-first;
T *now=first;
for(int i=0;i<len;i++)
{
cout<<*now;
now++;
}
cout<<endl;
}
//获取元素
T &at(int pos)
{
return first[pos];
}
//获取长度
int len()
{
return this->last-this->first;
}
//获取容量
int size()
{
return this->end-this->first;
}
};
int main()
{
MyVector<int> s1;
s1.push_back(1);
s1.push_back(2);
s1.push_back(3);
s1.push_head(4);
s1.push_head(5);
s1.push_head(6);
s1.show();
s1.del_back();
s1.del_head();
s1.show();
cout<<s1.at(3)<<endl;
cout<<s1.len()<<endl;
cout<<s1.size()<<endl;
return 0;
}
封装LIST
于 2023-04-04 19:35:22 首次发布