#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T*first;//向量的第一个元素的指针
T*last;//向量最后一个元素的指针
T*end;//指的是分配给向量空间末尾的下一个指针
public:
Myvector():first(new T[10]),last(first),end(first+10){cout<<"有参构造"<<endl;};//有参构造
//拷贝构造
Myvector ( const Myvector &other)
{
int size=other.last-other.first;
first=new T[size];
for(int i=0;i<size;i++)
{
first[i]=other.first[i];
}
last=first+size-1;
end=first+2*size;
cout<<"拷贝构造"<<endl;
}
//析构函数
~Myvector(){delete [] first;cout<<"析构函数"<<endl;}
//拷贝赋值
Myvector<T>&operator=(const Myvector<T>&other)
{
if(this!=&other)
{
delete [] first;
int size=other.size();
first=new T[size];
for(int i=0;i<size;i++)
{
first[i]=other.first[i];
}
last=first+size;
end=first+2*size;
}
return *this;
}
//元素个数
int size() const
{
return last - first ;
}
//容纳最大元素个数
int capacity()const
{
return end-first;
}
//查找任意值
T&at(int index)const
{
if(index<0||index>= size())
throw std::out_of_range("index out of range");
return first[index];
}
//判空
bool isempty()const
{
return size()==0;
}
//判满
bool isfull()const
{
return size()==capacity();
}
//返回第一个元素
T & front()const
{
if(isempty())
throw std::out_of_range("The vector is empty");
return *first;
}
//返回最后一个元素
T & lack()const
{
if(isempty())
throw std::out_of_range("The vector is empty");
return *last;
}
//清空向量
void clear()
{
delete [] first;
first=last=end=nullptr;
}
//二倍扩容
void expand()
{
int s=size();
T *new_first=new T[2*s];
memcpy(new_first,first,sizeof (T)*s);
delete [] first;
first=new_first;
last=first+s;
end=first+2*s;
}
//尾插
void push_back(const T&other)
{
if(isfull())
throw std::out_of_range("The vector is full");
*(last++)=other;
}
//尾删
void pop_back()
{
if(isempty())
throw std::out_of_range("The vector is empty");
--last;
}
};
int main()
{
//创建一个新的整形向量
Myvector<int> v1;
//尾插
// cout<<"向量大小:"<<v1.size()<<endl;
for(int i=1;i<=5;++i)
{
v1.push_back(i);
}
cout<<"V1 向量实际大小:"<<v1.size()<<endl;
cout<<"V1 向量容量:"<<v1.capacity()<<endl;
//拷贝构造
Myvector<int>v2=v1;
cout<<" V2 向量实际大小:"<<v2.size()<<endl;
cout<<"V2 向量容量:"<<v2.capacity()<<endl;
//二倍扩容
v1.expand();
cout<<"扩容 向量实际大小:"<<v1.size()<<endl;
cout<<"扩容 向量容量:"<<v1.capacity()<<endl;
//查找第一个元素
cout<<"查找第一个元素"<<v1.at(1)<<endl;
//尾删
v1.pop_back();
cout<<"尾删 向量实际大小:"<<v1.size()<<endl;
cout<<"尾删 向量容量:"<<v1.capacity()<<endl;
//清空向量
v2.clear();
cout<<" V2 清空后 向量实际大小:"<<v2.size()<<endl;
return 0;
}
输出结果: