#include <iostream>
using namespace std;
template <typename T>
class myvector
{
private:
T data;
size_t size;
public:
T *begin;
T *end;
T *last;
public:
myvector():data(0),size(0),begin(new T [0]),end(begin),last(begin+1){}
myvector(size_t num,const T &val):data(val),size(num)
{
begin=new T [size];
last=begin+size;
for(end=begin;end!=last;end++)
{
*end=val;
}
}
myvector( const myvector &from ):size(from.size)
{
begin=new T [size];
end=begin;
last=begin+size;
for(size_t i=0;i<size;i++)
{
*end=from.begin[i];
end++;
}
}
~myvector()
{
delete [] begin;
}
size_t mysize()
{
return end-begin;
}
size_t capacity()
{
return last-begin;
}
bool empty()
{
return (begin==end)?true:false;
}
void push_back( const T &val)
{
if(end==last)
{
size= last-begin;
T *temp=new T [(last-begin)*2];
memcpy(temp,begin,sizeof (T)*(last-begin));
delete [] begin;
begin = temp;
end = begin + size;
last= begin+2*size;
size=size*2;
}
*end++=val;
}
void push_pop( )
{
end--;
}
void slinsert(int loc,T val)
{
if(end==last)
{
size=last-begin;
T *temp=new T [(last-begin)*2];
memcpy(temp,begin,sizeof (T)*(last-begin));
delete [] begin;
begin = temp;
end = begin + size;
last=begin+2*size;
size=size*2;
}
end++;
for(int i=end-begin-1;i>=loc;i--)
{
begin[i+1]=begin[i];
}
begin[loc]=val;
}
T at(int n)
{
if(n>end-begin-1)
{
throw -1;
}
return begin[n];
}
T front()
{
return begin[0];
}
T back()
{
return begin[end-begin-1];
}
};
int main()
{
myvector<int>v1;
if(v1.empty())
{
cout<<"empty"<<endl;
}else
{
cout<<"not empty"<<endl;
}
for(int i=1; i<=20; i++)
{
v1.push_back(i);
cout<<"v1.size = "<<v1.mysize()<<" v1.capaticy = "<<v1.capacity()<<endl;
}
for(int i=0; i<v1.mysize(); i++)
{
cout<<v1.begin[i]<<" "; //[]不会进行下标越界检查
}
cout<<endl;
v1.slinsert(0, 520);
for(int i=0; i<v1.mysize(); i++)
{
cout<<v1.begin[i]<<" "; //[]不会进行下标越界检查
}
cout<<endl;
try {
cout<<v.at(21)<<endl;
} catch (int e) {
if(e==-1)
cout<<"超出范围"<<endl;
}
return 0;
}
c++作业
于 2023-04-25 21:01:01 首次发布