Help fix pop_back function for int vector

The 3rd to last line is reporting the incorrect size.

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream> 
#include <cstdlib>
using namespace std; 

class Vector
{
//member variables
private:
	int * ptr;
	int vecIndex;
	int vectSize;

	void grow()
	{
		int *temp = new int[vectSize + 1];
		for (int i = 0; i < vecIndex; i++)
			temp[i]=ptr[i];

		delete [] ptr;
		ptr = temp;
		vectSize += 1;
	}

	void shrink()
	{
		int *temp = new int[vectSize];
		for (int i = 0; i < vectSize; i++)
			temp[i] = ptr[i];
		
		delete [] ptr;
		ptr = temp;
		vectSize -= 1;
	}

//member functions
public:
	Vector()
	{
		ptr = new int[1];
		vecIndex = 0;
		vectSize = 1;

	}

	~Vector()	//destructors can't take any arguments.
	{
		delete [] ptr;
	}

	void pushVec(int value) //push_back??
	{
		if (vecIndex == vectSize)   
			grow();			//private, instead of public member, especially since it is only avaiable through public members instead of int main.

		ptr[vecIndex] = value;
		vecIndex++;
	}

	void popVec()	//pop_back
	{
		if (vectSize > 0 )
			shrink();
		else
			cout << "Vector size can't be lower than 0.";
	}

	int size()
	{
		return vecIndex;
	}

	int getIn(int index)
	{
		if (index < 0 || index >= vecIndex)
		{
			cout << "Error\n";
			//system("pause");
			//exit(0);
		}
		else
		{
			return ptr[index];
		}
	}
};


int main() 
{ 
	Vector number;
	number.pushVec(2);
	number.pushVec(5);	//
	number.pushVec(7);
	number.pushVec(8);

	cout << "Vector size " << number.size() << endl;
	cout << number.getIn(2) << endl;	// 7
	cout << number.getIn(3) << endl;	// 8
	cout << number.getIn(0) << endl;	// 2
	//cout << number.getIn(4) << endl;	// error

	number.popVec();
	cout << "Vector size " << number.size() << endl;	// 3
	
	system("pause");
	return 0; 
}
Last edited on
Look at line 32 and 69 then report what you find.
Topic archived. No new replies allowed.