手动实现My_vector
#include <iostream>
using namespace std;
template <typename T>
class my_vector
{
private:
T * first=nullptr;
T * last=nullptr;
T * end=nullptr;
int len=0;
int siz=0;
public:
//无参构造函数
my_vector(){cout<<"无参"<<endl;}
//析构函数
~my_vector()
{
delete []first;
delete []last;
delete []end;
}
//拷贝构造
my_vector(const my_vector &from)
{
//
first=new T[from.max()];
last=first;
end=first+from.max();
for(int i=0;i<from.size();i++)
{
*(last+i)=*(from.first+i);
}
last++;
}
//拷贝赋值
my_vector& operator=(const my_vector &from)
{
delete []first;
first=new T[from.max()];
last=first;
end=first+from.max();
for(int i=0;i<from.size();i++)
{
*(last+i)=*(from.first+i);
}
last++;
return *this;
}
//at():返回指定位置的元素
T &at(int n)
{
if(n<0||n>=len)
{
cout<<"没有这个下标"<<endl;
// return;
}
else
{
return *(first+n);
}
}
//返回当前能存储的大小
int max()
{
return siz;
}
//empty():判断Vector是否为空
bool empty()
{
return len==0;
}
//full():判满
bool full()
{
return len==siz;
}
//front():返回第一个元素
T front()
{
if(empty())
{
cout<<"容器已空"<<endl;
return;
}
return *first;
}
//back()返回最末一个元素 函数返回当前vector最末一个元素的引用
T &back()
{
if(empty())
{
cout<<"容器已空"<<endl;
// return;
}
return *(last-1);
}
//size():返回Vector元素数量的大小
int size()
{
if(empty())
{
cout<<"容器已空"<<endl;
return -1;
}
return len;
}
//clear():清空所有元素
void clear()
{
if(empty())
{
cout<<"容器已空,没必要清"<<endl;
return;
}
first=last;
*first=0;
len=0;
}
//expand() 二倍扩容函数
void expand()
{
if(len==0)
{
first=new T;
// memcpy(frag,first,sizeof(T));
last=first;
end=first;
siz=1;
}
else
{
T* frag=new T[len*2];
memcpy(frag,first,sizeof(T)*len);
delete []first;
first=frag;
last=frag+len;
end=frag+(len*2);
siz=len*2;
}
}
//push_back():在Vector最后添加一个元素
void push_back(T n)
{
if(full())
{
expand();
}
*last=n;
last++;
len++;
}
//pop_back():移除最后一个元素
void pop_back()
{
if(empty())
{
cout<<"容器已空"<<endl;
return;
}
last--;
}
//遍历函数
void show()
{
for(int i=0;i<size();i++)
{
cout<<*(first+i)<<" ";
}
cout<<endl;
}
};
int main()
{
my_vector<int> t;
for(int i=0;i<10;i++)
{
t.push_back(i);
cout<<t.max()<<endl;
}
}