Untitled
unknown
plain_text
10 months ago
2.9 kB
8
Indexable
#include<sstream>
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
class SafeVector {
T *ptr{};
int curoff{};
const int MAXSIZE=256;
int maxsize=0;
static vector<pair<T*,T*>> addr;
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 {
cout <<iptr<<endl;
int dist=-1;
for(int i=0;i<addr.size();i++){
if ((addr[i].first <=iptr) && (iptr<=addr[i].second)){
dist=iptr-addr[i].first;
break;
}
}
if(dist==-1)
return *iptr;
else
return *(addr.back().first+dist);
}
Iterator operator++(int) {
Iterator tmp{*this};
++(*this);
return tmp;
}
Iterator& operator++() {
++iptr;
return *this;
}
};
// Default constructor
SafeVector() {
ptr=new T[MAXSIZE];
maxsize=0;
curoff=0;
addr.clear();
}
// Initializer list constructor
SafeVector(initializer_list<T> init) {
addr.clear();
int len=init.size();
while(len>=maxsize) growby2();
curoff=0;
for(const T& x:init)
ptr[curoff++]=x;
}
// Destructor
~SafeVector() {
delete [] ptr;
maxsize=0;
addr.clear();
}
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;
addr.push_back({newptr,newptr+maxsize});
}
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;}
};
template<typename T>
vector<pair<T*,T*>> SafeVector<T>::addr;Editor is loading...
Leave a Comment