在这里我们实现了一个简易的vector,没有利用到 stl中的内存分配器,内存分配利用的是new进行分配。其余功能大致实现。
1 #ifndef _NVECTOR_ 2 #define _NVECTOR_ 3 #include<cstddef> 4 #include <algorithm> 5 template<typename T> 6 class nvector{ 7 public: 8 typedef T value_type; 9 typedef value_type* pointer; 10 typedef value_type& reference; 11 typedef value_type* iterator; 12 typedef size_t size_type; 13 typedef ptrdiff_t difference_type; 14 private: 15 iterator start; //迭代器的起始位置 16 iterator finish; 17 iterator end_of_storage; 18 void insert_aux(iterator position, const T& value); 19 public: 20 iterator begin(){return start;} 21 iterator end(){return finish;} 22 size_type size(){return size_type(end()-begin());} 23 size_type capacity(){return size_type(end_of_storage-begin());} 24 bool empty(){return start==finish;} 25 reference operator [](size_type index){return *(begin()+index);} 26 nvector():start(0),finish(0),end_of_storage(0){} 27 nvector(size_type n, const T& value){ 28 start = new T[n]; 29 for(int i=0;i<n;i++) 30 start[i] = value; 31 finish = start+n; 32 end_of_storage = start+n; 33 } 34 explicit nvector(size_type n){start = new T[n];finish = start; end_of_storage = start+n;} 35 ~nvector(){if(start!=NULL) delete[] start;finish=0;end_of_storage = 0;} 36 reference front(){return *begin();} 37 reference back(){return *(end()-1);} 38 void push_back(const T& value){ 39 if(finish!=end_of_storage){ 40 *finish = value; 41 ++finish; 42 }else 43 insert_aux(finish, value); 44 } 45 void pop_back(){ 46 if(!empty()) 47 --finish; 48 } 49 void clear(){ 50 finish = start; 51 } 52 }; 53 54 template<typename T> 55 void nvector<T>::insert_aux(iterator position,const T& value){ 56 if(finish!=end_of_storage){ 57 T x_copy = value; 58 copy_backward(position,finish,finish+1); 59 *position = x_copy; 60 }else{ 61 const size_type old_size = size(); 62 const size_type new_size = old_size!=0?2*old_size:1; 63 iterator new_start = new T[new_size]; 64 iterator new_finish = copy(start,position,new_start); 65 T x_copy = value; 66 *new_finish = x_copy; 67 ++new_finish; 68 new_finish = copy(position,finish,new_finish); 69 if(start!=NULL) 70 delete[] start; 71 start = new_start; 72 finish = new_finish; 73 end_of_storage = start+new_size; 74 } 75 } 76 77 #endif
时间: 2024-10-11 00:50:43