手动实现my_Vector
代码
#include <iostream>
using namespace std;
template <typename T>
class My_vector
{
private:
T* start;
T* last;
T* end;
public:
//初始化
My_vector(int size=2)
{
start=new T [size];
last=start;
end=start+size;
}
//析构函数
~My_vector()
{
delete []start;
start=last=end=nullptr;
}
//拷贝构造
My_vector(const My_vector &r)
{
//原来空间
int size=r.last-r.start;
int len=r.end-r.start;
//申请新空间
start = new T[len];
memcpy(start,r.start,sizeof (T)*size);
last=start+size;
end=start+len;
}
//拷贝赋值
My_vector &operator=(const My_vector &r)
{
if(this!=&r)
{
this->start=r.start;
this->last=r.last;
this->end=r.end;
}
return *this;
}
//判空
bool empty()
{
return last==start?1:0;
}
//判满
bool full()
{
return end==last?1:0;
}
//求大小
int size()
{
return last-start;
}
//数组长度
int len()
{
return end-start;
}
//尾插
void push_back(const T e)
{
if(full())
{
expand();
}
*last=e;
last++;
}
//二倍扩容
void expand()
{
//原来数组的总长度
int len=end-start;
T *t=new T[len*2];
memcpy(t,start,sizeof(T)*len);
delete []start;
start=t;
last=start+len;
end=start+len*2;
}
//尾部删除数据
void pop_back()
{
if(empty()==true)
{
cout<<"empty"<<endl;
return ;
}
--last;
}
//at访问成员
T& at(int pos)
{
if(pos<0||pos>size())
{
cout<<"pos错误"<<endl;
}
return start[pos];
}
//获取第一个元素
T front()const
{
return *start;
}
T back()const
{
return *last;
}
void clear()
{
start=last=0;
}
};
int main()
{
My_vector<int> v1;
cout<<"size="<<v1.size()<<" len="<<v1.len()<<endl;
//push_back函数:尾插
for(int i=0; i<20; i++)
{
v1.push_back(i+1);
cout<<"size="<<v1.size()<<" len="<<v1.len()<<endl;
}
//pop_back:尾删
v1.pop_back();
cout<<"size="<<v1.size()<<" len="<<v1.len()<<endl;
//遍历
for(int i=0; i<v1.size(); i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
My_vector<int> v2;
v2=v1; //拷贝赋值
cout<<"size="<<v2.size()<<" len="<<v2.len()<<endl;
for(int i=0; i<v2.size(); i++)
{
cout<<v2.at(i)<<" ";
}
cout<<endl;
//清空所有元素:clear()
v1.clear();
cout<<"size="<<v1.size()<<" len="<<v1.len()<<endl;
//判空函数:empty
if(v1.empty())
{
cout<<"v1.vector is empty"<<endl;
}else
{
cout<<"v1.vector is not empty"<<endl;
}
//判满函数:full
if(v1.full())
{
cout<<"v1.vector is full"<<endl;
}else
{
cout<<"v1.vector is not full"<<endl;
}
//返回第一个元素与返回第二个元素
cout<<"v2第一个元素值为:"<<v2.front()<<endl;
cout<<"v2最后一个元素值为:"<<v2.back()<<endl;
return 0;
}
结果