Not printing out correct values

Why is it not printing out the right values? I'm lost. Need help. Thanks.

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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <iostream>
#include <cstdlib>            
 

class cs234
{
public:
	template <typename T>
	class vector
	{
	public:

		vector() {}
		void push_back(T a)
		{

			if (size_m == 0)
			{
				capacity = 1;
			}
			size_m++;
			if (capacity == size_m)
			{
				capacity = capacity * 2;
				v = new T[capacity];
			}
			v[size_m] = a;

		}
		vector(const vector& b)
		{
			size_m = b.size_m;
			capacity = b.capacity;
			v = new T[capacity];
			for (int i = 0; i < size_m; i++)
			{
				this->v[i] = b.v[i];
			}

		}
		~vector()
		{
			if (v != NULL)
			{
				delete[] v;
				v = NULL;
			}
		}
		const  T& operator [](int i)  const
		{
			return v[i];
		}
		bool empty()
		{
			return (size_m == 0);

		}
		int pop_back()
		{
			return v[--size_m];
		}

		friend void Print(const vector<float >& rp)
		{
			for (int i{ 0 }; i < rp.size(); i++)
			{
				std::cout << rp[i] << " ";

			}
		}
		size_t size() const
		{
			return size_m;
		}
	private:
		T* v;
		int capacity = 0;
		size_t size_m = 0;
	};


};
 

void TestPush(void)
{
    std::cout << "\n********** TestPush **********\n";
    cs234::vector<float> a;
    std::cout << "Empty array:\n";
    Print(a);

    std::cout << "push_back 5 floats:\n";
    for (float i = 0; i < 5; i++) {
        a.push_back(i);
        Print(a);
    }

    std::cout << "pop_back until empty:\n";
    while (!a.empty()) {
        a.pop_back();
        Print(a);
    }
}

 
int main(int argc, char **argv)
{
    int test_num = 0;
    if (argc > 1)
        test_num = std::atoi(argv[1]);

    typedef void (*Test) (void);
    Test Tests[] = {
        TestPush,               //  1
       

    };
    int num = sizeof(Tests) / sizeof(*Tests);
    if (test_num == 0) {
        for (int i = 0; i < num; i++)
            Tests[i] ();
    } else if (test_num > 0 && test_num <= num)
        Tests[test_num - 1] ();
}
Last edited on
What are "the right values"?

What is it printing out, and how do they differ from what you expect?

We're not psychics!
In push_back you write the value to the wrong location in the array and you forgot to copy the elements to the new array when the capacity change.
Last edited on
Topic archived. No new replies allowed.