In my following program I tried to create a class similar to vector in c++. The function access in class Array is used to get element in array. The function pushback() is similar to push_back() function in vector and popback() is similar to pop_back() in vector. I am not able to delete last elements using popback() function. In popback() function delete [] arry seems to be the problem as it is not deleting all elements in arry.
Code:
#include <iostream>
#include <set>
#include <string>
#include <string.h>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath>
#include <climits>
#include <cctype>
using namespace std;
class Array{
public:
int *arry;
int sizeofarray;
Array(){
sizeofarray=0;
arry = new int[sizeofarray];
}
int access(int index){
return arry[index];
}
void pushback(int element){
int *temparray= new int[sizeofarray+1];
for(int i=0;i<sizeofarray;i++){
temparray[i]=arry[i];
}
temparray[sizeofarray]=element;
delete [] arry;
arry= new int[++sizeofarray];
for(int i=0;i<sizeofarray;i++){
arry[i]=temparray[i];
}
delete temparray;
}
void popback(){
int *temparray= new int[sizeofarray-1];
for(int i=0;i<sizeofarray-1;i++){
temparray[i]=arry[i];
}
delete [] arry;
sizeofarray--;
arry= new int[sizeofarray];
for(int i=0;i<sizeofarray;i++){
arry[i]=temparray[i];
}
delete temparray;
}
int sizey(){
return sizeofarray;
}
};
int main(){
Array myfirstvector;
//I assigned following to create an example of my problem
myfirstvector.pushback(9);
myfirstvector.pushback(2);
myfirstvector.pushback(3);
myfirstvector.pushback(4);
myfirstvector.pushback(7); //This element is not deleting
myfirstvector.popback();
myfirstvector.popback();
cout<<myfirstvector.access(0)<<" "<<myfirstvector.access(1)<<" "<<myfirstvector.access(2)<<" "<<myfirstvector.access(3)<<" "<<myfirstvector.access(4)<<" "
<<myfirstvector.access(6)<<endl;
cout<<"Size of array"<<myfirstvector.sizey()<<endl;
}
Output I get:
9 2 3 0 7 651317883
Size of array3
Output I expect:
9 2 3 garbagevalue grabagevalue garbagevalue
Size of array3
I tried modifying popback() function but still could not resolve my issue. I expect the popback() function to work similar to pop_back in vector.