Here we implement a simple vector that does not take advantage of the memory allocator in the STL, where memory allocations are allocated using new. The remaining features are broadly implemented.
1 #ifndef _nvector_2 #define_nvector_3#include <cstddef>4#include <algorithm>5Template<typename t>6 classnvector{7 Public:8 typedef T VALUE_TYPE;9typedef value_type*pointer;Tentypedef value_type&reference; Onetypedef value_type*iterator; A typedef size_t Size_type; - typedef ptrdiff_t DIFFERENCE_TYPE; - Private: theIterator start;//the starting position of the iterator - iterator finish; - iterator end_of_storage; - voidInsert_aux (iterator position,Constt&value); + Public: -Iterator begin () {returnstart;} +Iterator End () {returnfinish;} ASize_type size () {returnSize_type (End ()-begin ());} atSize_type capacity () {returnSize_type (end_of_storage-begin ());} - BOOLEmpty () {returnstart==finish;} -Referenceoperator[] (Size_type index) {return* (Begin () +index);} -Nvector (): Start (0), Finish (0), End_of_storage (0){} -Nvector (size_type N,Constt&value) { -Start =NewT[n]; in for(intI=0; i<n;i++) -Start[i] =value; tofinish = start+N; +End_of_storage = start+N; - } the ExplicitNvector (size_type N) {start =NewT[n];finish = start; End_of_storage = start+N;} *~nvector () {if(Start!=null)Delete[] start;finish=0; end_of_storage =0;} $Reference Front () {return*begin ();}Panax NotoginsengReference back () {return* (End ()-1);} - voidPush_back (Constt&value) { the if(finish!=end_of_storage) { +*finish =value; A++finish; the}Else + Insert_aux (finish, value); - } $ voidPop_back () { $ if(!empty ()) ---finish; - } the voidClear () { -finish =start;Wuyi } the }; - WuTemplate<typename t> - voidNvector<t>::insert_aux (iterator position,Constt&value) { About if(finish!=end_of_storage) { $T x_copy =value; -Copy_backward (position,finish,finish+1); -*position =x_copy; -}Else{ A ConstSize_type old_size =size (); + ConstSize_type new_size = old_size!=0?2*old_size:1; theIterator New_start =NewT[new_size]; -Iterator New_finish =copy (Start,position,new_start); $T x_copy =value; the*new_finish =x_copy; the++New_finish; theNew_finish =copy (position,finish,new_finish); the if(start!=NULL) - Delete[] start; inStart =New_start; thefinish =New_finish; theEnd_of_storage = start+new_size; About } the } the the #endif
The realization of simple vector