今天想学一下stl里面的向量容器vector,写一下它的j简单实现方式:
template<typename T>
class CVector
{
public:
//vector的默认构造函数不开辟内存的
CVector()::mpVec(NULL),mEnd(0),mlast(0){}
~CVector()
{
delete []mpVec;//释放空间
mpVec = NULL;
}
void push_back(const T &val)
{
if(full())
{
cout<<"resize max"<<endl;
resizeMem();//空间满了就扩容
}
mpVec[mLast++] = val;//后插添加元素
}
void pop_back()
{
if(!empty())
{
--mLast;//出元素时并不释放其空间
}
}
int size()const
{
return mLast;
}
bool full()const
{
return mLast == mEnd;
}
bool empty()const
{
return mLast == 0;
}
void reserve(int size)
{
//在默认构造函数vector上预留空间
mpVec = new T[100];
mEnd = size;
mLast = 0;
}
void resize(int size)
{
//在默认构造的vector上resize
mpVec = new T[100];
mEnd = size;
mLast = size;
}
class iterator//迭代器
{
public:
iterator(T *ptr = NULL):_ptr(ptr){}
bool operator !=(const iterator &it)
{
return _ptr != it._ptr;
}
void operator++()
{
++_ptr;
}
T&operator*()
{
return *_ptr;
}
private:
T *_ptr;
};
iterator begin()
{
return mpVec;
}
iterator end()
{
return mpVec + suze();
}
T*mpVec;
int mEnd;
void resizeMem()
{
if(mpVec == NULL)
{
mpVec = new T[1];
mEnd = 1;
mLast = 0;
}
else
{
//resize只考虑容器满了以后,内存2倍增长的情况
T *ptmp = new T[2*size()];
memcpy(ptmp,mpVec,sizeof(T)mLast);
mEnd*=2;
delete []mpVec;
mpVec = ptmp;
}
}
};