vector of int class..

Hello, on an attempt to create a class which is basically a mimic of vector<int> i don't seem to know how to delete pointer x in a destructor to free memory, also on pushback and pushfront methods, i can't free y when i implement delete[] y; y=NULL; i get some NULL out put when cout 'ing the object in main, i would really appreciat knowing why is that happening and how do i free memory y. Or is it freed automatically as the method exits? and feel free to give feedbacks on my coding :)
Thanks for your time.






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<iostream>
using namespace std;

class vectorOfint{
	int* x;
	int size;
	public:
		vectorOfint();
		vectorOfint(int size);
		int get(int index);
		void set(int index, int value);
		void pushback(int value);
		void pushfront(int value);
		~vectorOfint();
		
};
vectorOfint::~vectorOfint()
{
	delete[] x;
	x=NULL;
	
}
vectorOfint::vectorOfint():x(new int[32]),size(32){};
vectorOfint::vectorOfint(int size):x(new int[size]),size(size){};
int vectorOfint::get(int index){return x[index];};
void vectorOfint::set(int index, int value){x[index]=value;};
void vectorOfint::pushback(int value)
{
	size++;
	int *y=new int[size];
	for(int i=0;i<size-1;i++)
	y[i]=x[i];
	
	y[size-1]=value;
	
	x=y;
}
void vectorOfint::pushfront(int value)
{
	size++;
	int *y=new int[size];
	y[0]=value;
	for(int i=0,j=1;j<size;i++,j++)
	y[j]=x[i];
	
	x=y;
	
}


int main()
{
	vectorOfint x(10);
	for(int i=0;i<10;i++)
	x.set(i,i+1);
	
	x.pushfront(50);
	x.pushback(100);
	for(int i=0;i<12;i++)
	cout<<x.get(i)<<endl;
	
	
	
	return 0;
}
And how can i handle negative size input in the constructor or in get, set methods?
Last edited on
Throw an exception.
> how can i handle negative size input in the constructor or in get, set methods?

Consider using an unsigned integral type:
1
2
3
vectorOfint( unsigned int size);
int get( unsigned int index);
void set( unsigned int index, int value);

In get() and set(), you will still have to check for index values that are too large.
Aha thanks, now how to get rid of pointer Y allocated memory?
You don't want to get rid of y's allocated memoty. You assign y to x at line 36. If you delete y, you will be deleting what x also points to.

What you are missing is a delete of the old x at line 45.
Last edited on
1
2
delete[] x ; // discard the old buffer
x = y ; // from now-on, use the newly allocated (larger) buffer 
.

Consider giving more meaningful names to your variables.
Topic archived. No new replies allowed.