Untitled
#include<sstream> #include<iostream> 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{}; T val; public: Iterator(T* xptr=nullptr):iptr(xptr),val(iptr?*iptr:0) {} 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*() { return val; } Iterator operator++(int) { Iterator tmp{*this}; ++(*this); return tmp; } Iterator& operator++() { ++iptr; val=*iptr; return *this; } }; // Default constructor SafeVector() { maxsize=0; curoff=0; while(curoff>=maxsize) growby2(); } // Initializer list constructor SafeVector(initializer_list<T> init) { maxsize=0; int len=init.size(); while(len>=maxsize) growby2(); curoff=0; for(const T& x:init) ptr[curoff++]=x; } // Destructor ~SafeVector() { delete [] ptr; maxsize=0; } void growby2(){ T* newptr = new T[maxsize*2+2]{}; for(int i=0;i<maxsize;i++) newptr[i]=ptr[i]; maxsize = maxsize*2 + 1; delete [] ptr; ptr=newptr; } void moveright(int idx){ while(curoff>=maxsize-1) growby2(); for(int j=curoff;j>=idx;j--) ptr[j+1]=ptr[j]; curoff++; } // Array subscript operator T& operator[](size_t index) { return ptr[index]; } // Add element to the end void push_back(const T& ele) { while(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+curoff;} };
Leave a Comment