#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(const Myvector<T> &v):first(nullptr),last(nullptr),end(nullptr)
{
first=new T[v.capacity()]; //分配内存空间
end=first +v.capacity();
last=first +v.size();
for(int i=0;i<v.size();++i) //复制原有的数据
{
first[i]=v.first[i];
}
}
//拷贝赋值函数
Myvector& operator=(const Myvector &v)
{
delete[] first; //释放空间
first=new T[v.capacity()]; //分配内存空间
end=first +v.capacity();
last=first +v.size();
for(int i=0;i<v.size();++i) //复制原有的数据
{
first[i]=v.first[i];
}
return *this;
}
//析构函数
~Myvector()
{
delete[] first;
}
//遍历
void show() {
for(auto p=first; p!=last; p++) {
cout<<*p<<" ";
}
cout<<endl;
}
//at函数
T& at(int index)
{
if(index<0 || index >= size())//越界
{
throw "Index out of range";//报错
}
return first[index];
}
//empty函数
bool empty() const
{
return first ==last;
}
//full函数
bool full() const
{
return last==end;
}
//front 函数
T& front()
{
return *first;
}
//back函数
T& back()
{
return *(last-1);
}
//size函数
int size() const
{
return last-first;
}
//clear函数
void clear()
{
last=first;
}
//expand函数
void expand()
{
int capacity =end-first;//计算当前容量
T *new_first=new T[capacity *2];//分配新的空间
T *new_last=new_first+size();//将原有数据偏移
for(int i=0;i<size();++i)//复制原有的数据
{
first[i]=first[i];
}
delete[] first;//释放原有空间
first =new_first;
last =new_last;
end=first+capacity *2;
}
//push_back函数
void push_back(const T &value)
{
if(full())//空间不足,进行二倍扩容
{
expand();
}
*last++=value;
}
// pop_back函数
void pop_back()
{
if (empty()) // 空间为空,错误处理
{
throw "Vector is empty";
}
--last;
}
};
int main()
{
Myvector<int> v1;
cout<<boolalpha;
cout <<"empty="<< v1.empty() << endl;
cout <<"size="<< v1.size() << endl;
cout <<"full="<< v1.full() << endl;
v1.push_back(10);
v1.push_back(20);
v1.push_back(30);
v1.push_back(40);
v1.show();
v1.push_back(50);
cout << v1.at(1) << endl;
try
{
cout <<"at="<< v1.at(2) << endl;
} catch (string s)
{
cout <<"s="<< s << endl;
}
v1.at(0) = 30;
v1.at(v1.size() - 1) = 40;
cout <<"front="<< v1.front() << endl;
cout <<"back="<< v1.back() << endl;
v1.pop_back();
v1.clear();
cout <<"empty="<< v1.empty() << endl;
return 0;
}