Untitled
#include<sstream> using namespace std; template<typename T> class SafeVector { T *ptr{}; int curoff{}; const int MAXSIZE=256; int maxsize=0; public: class Iterator { // Iterator implementation T *iptr{}; public: Iterator(T* xptr=nullptr):iptr(xptr) {} int operator-(Iterator it1){ return iptr - it1.iptr; } Iterator operator+(int x){ return iptr+x; } bool operator==(Iterator it1) const { return iptr==it1.iptr; } bool operator!=(Iterator it1) const { return iptr!=it1.iptr; } T& operator*() const { return *iptr; } Iterator operator++(int) { Iterator tmp{iptr}; ++(*this); return tmp; } Iterator& operator++() { ++iptr; return *this; } }; // Default constructor SafeVector() { ptr=new T[MAXSIZE]; maxsize=0; curoff=0; } // Initializer list constructor SafeVector(initializer_list<T> init) { curoff=0; for(const T& x:init) ptr[curoff++]=x; } // Destructor ~SafeVector() { delete [] ptr; maxsize=0; } void growby2(){ T* newptr = new T[maxsize*2+1]; for(int i=0;i<maxsize;i++) newptr[i]=ptr[i]; maxsize=maxsize*2 + 1; delete [] ptr; ptr=newptr; } void moveright(int idx){ if(curoff>=maxsize-1){ growby2(); } for(int j=curoff;j>=idx;j--) ptr[j+1]=ptr[j]; } // Array subscript operator T& operator[](size_t index) { return ptr[index]; } // Add element to the end void push_back(const T& ele) { if(curoff>=maxsize) growby2(); ptr[curoff++]=ele; } // Insert element at iterator position void insert(Iterator pos, const T& value) { int d=pos-ptr; moveright(d); ptr[d]=value; } // Get iterator to first element Iterator begin() { return ptr;} // Get iterator to position after last element Iterator end() { return ptr+maxsize;} };
Leave a Comment