1 //vector -- simple vector, @CopyLeft by tsaiwn@csie.nctu.edu.tw 2 //Demo how vector works; 但這簡易版不會丟出 Exception 3 #ifndef __MY_VECTOR__ 4 #define __MY_VECTOR__ 5 //to ensure this file will be only "included" once 6 #include 7 #include // sort( ) 8 #include // standard exception classes 9 using namespace std; 10 11 template 12 class vector { 13 T* pdata; // pointer can be used like an array 14 int _size, _capc; // store my size and my capacity 15 void getMoreSpace( ) { //get new memory, copy old to new, drop old 16 _capc += _capc; // double space 17 T* p = new T[_capc]; 18 T *old = pdata; // for later use 19 pdata = p; // point to new data Area 20 memcpy((void*)pdata, (void*)old, (sizeof(T) * _size)); // byte 21 delete [ ] old; // release Old data memory area 22 return; // done 23 }//getMoreSpace( 24 public: 25 typedef T* iterator; 26 vector(int n=10) {_size=0; _capc=n; pdata = new T[_capc]; } 27 // default initial capacity in C++ STL is 0; in Java is 10 28 vector(T*a, T*b) { 29 _size=_capc= b-a; 30 pdata = new T[_capc]; 31 memcpy((void*)pdata, (void*)a, (sizeof(T) * _size)); // byte 32 } // constructor 33 int size( ) { return _size; } 34 int capacity( ) { return _capc; } 35 T* begin( ) { return pdata; } 36 T* end( ) { return pdata+ _size; } 37 T& front( ) { return *pdata; } 38 T& back( ) { return pdata[_size-1]; } // *(pdata+ _size -1) 39 void push_back(const T a) { 40 if( _size == _capc ) getMoreSpace( ); // ensure enough space 41 pdata[_size] = a; // append data into tail 42 _size++; // advance one data unit 43 }//push_back 44 void pop_back( ) { 45 if( _size <= 0 ) return; // Nothing in the vector 46 _size--; 47 }//pop_back 48 void add(const T a) { push_back(a); } // nick name 49 T& operator[ ](int n) { cout <<" X "; return pdata[n]; } ///// 50 T& at(int n) { cout <<" A "; 51 if(n < 0) throw range_error("vector"); 52 if(n >= _size) throw range_error("vector"); 53 return pdata[n]; 54 } // at( 55 // Note that the operator[ ] and at function should return reference, 56 // .. so that it can be used as a "Left value" 57 }; // class vector 58 #endif