#include <iostream>
using namespace std;
template <class T>
class Myvector
{
private:
T *first;
T *last;
T *end;
// int n;
public:
Myvector():first(nullptr),last(nullptr),end(nullptr) {} //无参构造
// Myvector(T *f,T *l,T * e):first(f),last(l),end(e) {} //有参构造
Myvector(int n,T s) //有参构造
{
first = new T(n);
end = first;
last = first+n;
for(int i=0;i<n;i++)
{
*(end++) = s;
// first++;
}
}
~Myvector() //析构函数
{
delete []first;
first = last = end = nullptr;
}
void at(int n) //任意位置的值
{
if(n<0||n>=(end-first))
{
throw string("out of range");
}
cout<<*(first+n)<<endl;
}
bool empty() //判空
{
if(end == first)
{
// cout<<"为空"<<endl;
return true;
}
else
{
// cout<<"非空"<<endl;
return false;
}
}
bool full() //判满
{
if(end == last)
{
// cout<<"已满"<<endl;
return true;
}
else
{
// cout<<"非满"<<endl;
return false;
}
}
T &front() //返回当前vector起始元素的引用
{
return *first;
}
int& back() //返回当前vector最末一个元素的引用
{
return *end;
}
int size() //返回当前vector所能容纳元素的数目
{
cout<<"size = "<<end-first<<endl;
return end-first;
}
void clear() //删除当前vector中的所有元素
{
while(end!=first)
pop_back();
}
void expand() //二倍扩容
{
int len = last-first;
T*temp = new T(2*len);
memcpy(temp,first,sizeof(T)*(last-first));
delete []first;
first = temp;
end = first+len;
last = first+2*len;
}
void push_back(T a) //添加到当前vector的末尾
{
if(full()==1)
{
expand();
end++;
*(end-1)=a;
}
else
{
end++;
*(end-1)=a;
}
}
void pop_back() //删除当前vector的最末元素
{
if(empty()==1)
{
throw string ("vectory is empty");
}
else
{
end --;
*end = '\0';
}
}
void show()
{
for(int i=0;i<(end-first);i++)
{
cout<<*(first+i)<<" ";
}
cout<<endl;
}
};
int main()
{
try
{
Myvector<int>s1;
Myvector<int>s2(8,5);
s2.at(0);
// s2.empty();
s2.size();
// s2.at(t-1);
s2.pop_back();
s2.pop_back();
s2.size();
cout<<"***********************"<<endl;
s2.push_back(8);
s2.size();
s2.show();
cout<<"***********************"<<endl;
s2.push_back(8);
s2.size();
s2.show();
// cout << "Hello World!" << endl;
}
catch (string e)
{
cout<<e<<endl;
}
return 0;
}