我們知道,內存塊的大小是不能改變的,因此數組的大小不能改變。但是STL的vector讓我們擺脫了這種困擾,它可以幫我們動態的管理數組的大小。
誠然,STL的vector底層還是通過動態數組來實現的,當數組大小不夠時,就申請一塊更大的內存,同時將原來的元素的值拷貝過去,再刪掉原來那塊小內存,當然這一操作的帶價是非常高的,包括了一次申請內存和釋放內存,以及元素的初始化。
本文給出了Vector類模板的實現,相比於STL的vector模板當然差的遠了,但是大致原理差不多了,大家讀讀下面的代碼應該可以讓你對STL的vector的理解加深。
templateclass Vector{ public:
//構造函數,復制構造函數以及析構函數
Vector(int size=0):theSize(size),theCapacity(0+SPACE_CAPACITY){
objects=new T[theCapacity];
}
Vector(const Vector& rhs):objects(NULL){
operator=(rhs);
}
~Vector(){
delete[] objects;
}
// 重載=號操作符
const Vector& operator=(const Vector& rhs){
theCapacity=rhs.theCapacity;
theSize=rhs.theSize;
objects=new objects[this->theCapacity];
for(int i=0;itheSize;i++)
objects[i]=rhs.objects[i];
return *this;
}
//調整size
void resize(int newSize){
if(newSize>theCapacity)
reserve(newSize*2+1);
theSize=newSize;
}
//調整預留的空間,也就是實際上申請的內存的大小
void reserve(int newCapacity){
if(newCapacity//幾個get函數,均為const成員,保證const對象也能調用
bool isEmpty() const{
return getSize()==0;
}
int capacity() const{
return theCapacity;
}
int size() const{
return theSize;
}
//push和pop操作
void push_back(T t){
if(theSize==theCapacity)
reserve(theCapacity*2+1);
objects[theSize++]=t;
}
void pop_back(){
theSize--;
}
T& back(){
return objects[theSize-1];
}
const T& back()const{
return objects[theSize-1];
}
// 迭代器
typedef T* iterater;
typedef const T* const_iterater;
//begin end 等操作
iterater begin(){
return objects;
}
const_iterater begin() const{
return objects;
}
iterater end(){
return (objects+theSize);
}
const_iterater end() const{
return (objects+theSize);
}
enum { SPACE_CAPACITY=16};
private:
T* objects;
int theSize;
int theCapacity;
};
這裡稍微提一下 const成員函數,也稱常成員函數,或者只讀成員函數,const對象只能訪問常成員函數,通過const指針調用也只能訪問常成員函數,但是有個特例,構造函數和析構函數是唯一不是const成員函數卻可以被const對象調用的成員函數。