//vector -- simple vector, @CopyLeft by tsaiwn@csie.nctu.edu.tw //Demo how vector works; 但這簡易版不會丟出 Exception #ifndef __MY_VECTOR__ #define __MY_VECTOR__ //to ensure this file will be only "included" once #include #include // sort( ) #include // standard exception classes using namespace std; template class vector { T* pdata; // pointer can be used like an array int _size, _capc; // store my size and my capacity void getMoreSpace( ) { //get new memory, copy old to new, drop old _capc += _capc; // double space T* p = new T[_capc]; T *old = pdata; // for later use pdata = p; // point to new data Area memcpy((void*)pdata, (void*)old, (sizeof(T) * _size)); // byte delete [ ] old; // release Old data memory area return; // done }//getMoreSpace( public: typedef T* iterator; vector(int n=10) {_size=0; _capc=n; pdata = new T[_capc]; } // default initial capacity in C++ STL is 0; in Java is 10 vector(T*a, T*b) { _size=_capc= b-a; pdata = new T[_capc]; memcpy((void*)pdata, (void*)a, (sizeof(T) * _size)); // byte } // constructor int size( ) { return _size; } int capacity( ) { return _capc; } T* begin( ) { return pdata; } T* end( ) { return pdata+ _size; } T& front( ) { return *pdata; } T& back( ) { return pdata[_size-1]; } // *(pdata+ _size -1) void push_back(const T a) { if( _size == _capc ) getMoreSpace( ); // ensure enough space pdata[_size] = a; // append data into tail _size++; // advance one data unit }//push_back void pop_back( ) { if( _size <= 0 ) return; // Nothing in the vector _size--; }//pop_back void add(const T a) { push_back(a); } // nick name T& operator[ ](int n) { cout <<" X "; return pdata[n]; } ///// T& at(int n) { cout <<" A "; if(n < 0) throw range_error("vector"); if(n >= _size) throw range_error("vector"); return pdata[n]; } // at( // Note that the operator[ ] and at function should return reference, // .. so that it can be used as a "Left value" }; // class vector #endif