Here is a routine for implementation and application:
#include <iostream>using namespacestd;template<typename object>classvector{ Public: ExplicitVector (intInitsize =0): Thesize (Initsize), thecapacity (Initsize+spare_capacity) {Objects=Newobject[thecapacity];} Vector (ConstVector &rhs): Objects (NULL)//three major functions{operator=(RHS);} ~Vector () {Delete[] objects;} ConstVector &operator=(ConstVector &RHS) { if( This! = &RHS) { Delete[] objects; Thesize=rhs.size (); Thecapacity=rhs.thecapacity; Objects=Newobject[Capacity ()]; for(intK =0; K < size (); k++) Objects[k]=Rhs.objects[k]; } return* This; } voidResizeintNewSize)//Reset Size { if(NewSize >thecapacity) Reserve (NewSize*2+1 ); Thesize=newSize; } voidReserveintnewcapacity) { if(Newcapacity <thesize)return ; Object*oldarray =objects; Objects=Newobject[newcapacity]; for(intK =0; K < thesize; k++) Objects[k]=Oldarray[k]; Thecapacity=newcapacity; Delete[] oldarray; } Object&operator[](intIndex)//Subscript Reference{returnobjects[index];} ConstObject &operator[](intIndex)Const { returnobjects[index];} BOOLEmpty ()Const { returnSize () = =0; } intSize ()Const { returnthesize;} intCapacity ()Const { returnthecapacity;} voidPush_back (ConstObject &x) {if(Thesize = =thecapacity) Reserve (2* Thecapacity +1 ); Objects[thesize++] =x; } voidPop_back () {thesize--; } ConstObject &back ()Const { returnobjects[thesize-1]; } typedef Object*iterator; typedefConstObject *const_iterator; Iterator begin () {return&objects[0]; } const_iterator begin ()Const { return&objects[0]; } iterator End () {return&objects[size ()];} Const_iterator End ()Const { return&objects[size ()];} enum{spare_capacity = - }; Private: intthesize; intthecapacity; Object*objects;};intMain () {Vector<int>Num; cout<<"Enter a set of data:"<<Endl; inttemp; while(Cin >>temp) Num.push_back (temp); cout<<"The data you entered is:"<<Endl; Vector<int>::iterator iter =Num.begin (); for(; ITER! = Num.end (); + +iter) cout<< *iter <<" "; cout<<Endl; return 0;}
Simple variable-length array