I'm trying to implement an alternative to usual contiguous dynamic arrays, where I am using a vector of pointers, each is pointing to a constant size array, referring to it as XVector.
It works fine for a certain limit of inputs - say 150 elements -, but beyond that it starts throwing exceptions.
I tried to use "new and delete" instead of "malloc and free", it did increased the limit - say about 1200 elements -, but still exists the same problem.
I'm using C++.
Here's my main program:
XVector<int> xv;
for(int i=0;i<1210;i++){
int temp = rand()%100;
xv.pushBack(temp);
}
for(int i=0;i<xv.size();i++){
cout<<xv.getValue(i)<<" ";
}
cout<<"\n\n"<<xv.capacity();
return 0;
And here's is the XVector (The class of theD header file:
private:
const int b = 10;
vector<T*> arr;
int currentIndex;
int maxSize;
protected:
void expand(){
T* temp = new T[b];
arr.push_back(temp);
maxSize+=(b);
}
void shrink(){
delete[] arr[arr.size()-1];
arr[arr.size()-1] = NULL;
arr.pop_back();
maxSize-=(b);
}
int ceil(float num) {
int inum = (int)num;
if (num == (float)inum) {
return inum;
}
return inum + 1;
}
pair<int,int> position(int index){
pair<int,int> pos;
float result = ((float)index/b);
pos.first = result; //Row #
pos.second = ceil((result - pos.first)*b); //Exact cell in the row
return pos;
}
public:
XVector(){
currentIndex=0;
maxSize=b;
arr.reserve(120);
arr.push_back(new T[b]);
}
void pushBack(T value){
if(currentIndex>=maxSize-1){expand();}
pair<int,int> indeces = position(currentIndex);
arr[indeces.first][indeces.second]=value;
currentIndex++;
}
void popBack(){
currentIndex--;
if(maxSize>=currentIndex+(2*b)){shrink();}
}
T getValue(int index){
pair<int,int> indeces = position(index);
return arr[indeces.first][indeces.second];
}
void setValue(int index,T value){
pair<int,int> indeces = position(index);
arr[indeces.first][indeces.second] = value;
}
int capacity(){
return maxSize;
}
int size(){
return currentIndex;
}
bool empty(){
return currentIndex==0?true:false;
}
PS: I tried to use Valgrind, but failed to identify the exact problem.