#include <iostream>
using namespace std;
//定义一个模板类
template <typename T>
class myvector
{
private:
T *first;
T *last;
T *end;
public:
//构造函数
myvector(int n)
{
first=new T[n]; //申请空间
last=first; //说明容器为空
end=first+n; //空间尾指针
}
//析构函数
~myvector()
{
delete []first;
first=last=end=nullptr;
cout<<"myvector:析构函数"<<endl;
}
//拷贝函数
myvector(const myvector &other):first(new T(*(other.first))),last(new T(*(other.last))),end(new T(*(other.first)))
{
cout<<"拷贝函数"<<endl;
}
//拷贝赋值函数
myvector &operator=(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));
//将该对象的另外两个指针指向对应位置
last=first+len;
end=first+size;
cout<<"拷贝赋值函数"<<endl;
return *this; //返回自身的引用
}
//at():成员访问
T &at(int a)
{
if(a<0 && a>last-first) //判断a是否在范围内
{
cout<<"不在范围内"<<endl;
}
else
return first[a];
}
//判断当前myvector是否为空
bool empty()
{
return this->first==this->last;
}
//判断当前myvector是否为满
bool full()
{
return this->last==this->end;
}
//返回第一个元素的函数
T front()
{
return *first;
}
//元素个数的函数
int size()
{
return end-first;
}
//容器的容量
int len()
{
return last-first;
}
//清空所有元素的函数
void clear()
{
this->end=this->first;
}
//expand():二倍扩容函数
void expand()
{
int len = end-first;
T *temp = new T(2*len);
memcpy(temp,first,sizeof(T)*len);
delete []first;
first = temp;
last = first+len;
end = first + 2*len;
}
//push_back():尾插
void push_back(const T e)
{
if(true==full())
{
cout<<"容器已满,无法尾插"<<endl;
expand();
}
*last=e;
last++;
cout<<"尾插成功"<<endl;
}
//pop_back():尾删
void pop_back()
{
if(true==empty())
{
cout<<"容器为空,尾删失败"<<endl;
}
--last;
cout<<"删除失败"<<endl;
}
};
int main()
{
myvector<int> M(10); //类模板必须显性调用,在函数名后使用<>传递实参类型
M.push_back(11);
M.push_back(22);
M.push_back(33);
cout<<M.at(1)<<" ";
cout<<M.at(2)<<" ";
cout<<M.at(3)<<" "<<endl;
cout<<"容器中第一个元素为:"<<M.front()<<endl;
M.clear();
return 0;
}