1.自己封装vector
template<typename T>
class Myverctor
{
T* first;
T* last;
T* end;
public:
Myverctor():first(NULL),last(NULL),end(NULL){}
Myverctor(int num,T data):first(new T[num])
{
last = end = first + num;
for(int i = 0;i<num;i++) first[i] = data;
}
Myverctor(const Myverctor &v):first(new T[v.last-v.first]),
last(v.last),end(v.last)
{
for(int i = 0;first+i!=end;i++) first[i] = v.first[i];
}
~Myverctor()
{
delete [] first;
}
Myverctor & operator = (const Myverctor v)
{
delete [] first;
first = new T[v.last-v.first];
end = last = v.last;
for(int i = 0;first+i!=end;i++) first[i] = v.first[i];
return &this;
}
void expand()
{
if(end == first)
{
first = new T;
last = first;
end = first+1;
}
else
{
int len = end - first;
T* t = new T[2*len];
int i = 0;
for(;first+i!=last;i++) t[i] = first[i];
delete [] first;
first = t;
last = t+i;
end = t+2*len;
}
}
bool empty()
{
return last==first;
}
bool full()
{
return last==end;
}
T& at(int p)
{
try {
if(empty()) throw 1;
if(p<0||p>=last-first) throw 2;
else return first[p];
} catch (int e) {
if(e==1)
cout<<"vector为空"<<endl;
if(e==2)
cout<<"下标错误"<<endl;
}
}
T& front()
{
try {
if(empty()) throw 1;
else return *first;
} catch (int e) {
cout<<"vector为空"<<endl;
}
}
T& back()
{
try {
if(empty()) throw 1;
else return *last;
} catch (int e) {
cout<<"vector为空"<<endl;
}
}
int size()
{
return last-first;
}
void clear()
{
last = first;
}
void push_back(T t)
{
if(full()) expand();
*last++ = t;
}
void pop_back()
{
if(empty()) return;
last--;
}
};
2.思维导图