New operator with a vector class

I am working on a vector class to fill it with data. When I run the code it outputs the correct data in the void myVector::push_back(int valueIn) function but int the print function it out puts garbage values. I thought the arr pointer, which is a dynamic array, pointed to the same data in both functions. Any help would be appreciated.
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
#include "myVector.h"
#include <iostream>
using namespace std;

myVector::myVector()
{
	arr = new int[ 10 ];
	size = 0;
	capacity = 10;
}

myVector::~myVector()
{
	if (capacity >0)
	{
		delete []arr;
	}
	capacity = 0;
	size = 0;
}

// main is sending the valueIn data
void myVector::push_back(int valueIn)
{
	arr = &valueIn;
	cout << *arr << " "; // I used this cout to check if I had the right 
}                            // values, of which I do



void myVector::print()
{
	for( int i = 0; i < capacity; i++ )
	{
		cout << arr << " ";
	}
}

Your push back assigns the buffer to a pointer to a temporary value.
It should copy the buffer in a larger array, insert the argument as last element of that array and delete the old buffer.
This does not make sense:

1
2
3
4
5
void myVector::push_back(int valueIn)
{
    arr = &valueIn; //******** Here
    cout << *arr << " "; 
} 
I was trying to load the arr with the values sent in from valueIn. Evidently that is in correct.

I tried some other stuff but now my print function only prints out the number 18 "capacity" times which is the last number coming in from valueIn. valueIn is 2,4,6,8,10,12,14,16,18

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

void myVector::push_back(int valueIn)
{
	for( int i = 0; i < capacity; i++ )
		arr[ i ] = valueIn;
	
	cout << *arr << " ";  // I used this cout to check if I had the right 
}                                      // values, of which I do


void myVector::print()
{
	for( int i = 0; i < capacity; i++ )
		cout << arr[ i ] << " ";
}

// output to the screen is 18 18 18 18 etc. 



Bazzy I am not sure what your talking about as far as the buffer. Could you give an explanation or example?

Thanks
Last edited on
Well the push_back function only takes a single integer value - so a loop like
this:
1
2
for( int i = 0; i < capacity; i++ )
      arr[ i ] = valueIn;

is incorrect - all it does is fillup the array with the same value.

What you need to do is (I assume size hold the number of values already in the array):

1. Check if the array is full - if full - return an error (but your function is void and you would need to change that)

2. If there is space in the array - put the new value at the back of the array (as determined by the size value) - then increment the size value.


On another note:
In the print function, the loop should turn on the number of actual values in the array rather than the capacity

In all of the above, I am assuming size is the number of actual values in the array, and capacity
tells us how many it can possibly hold.

Thanks for the reply guestgulkan.
You're assumptions are correct about the size and capacity. I will play with it some more and see what else I can do.
I just did not understand how it would print out the correct values in the push_back() and the same 18 value in the print() but I think I got it know.

Thanks a lot. I am new at this stuff and some people treat newbies like they weren't newbies themselves at one point, so I appreciate the help.

You'll be hearing from me again :)

Thanks

Last edited on
I have played with this thing and man am I having fun. I got it to print the right output but when I run it I get an error saying the heap is corrupted. I think I need to use delete somewhere but I don't know where. Any ideas?

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
#include "myVector.h"
#include <iostream>
using namespace std;

myVector::myVector()
{
	arr = new int[ 5 ];
	size = 0;
	capacity = 5;
}

myVector::~myVector()
{
	if (capacity >0)
	{
		delete []arr;
	}
	capacity = 0;
	size = 0;
}

int myVector::getSize()
{
	return -1;
}
void myVector::push_back(int valueIn)
{ 
	if( size <= capacity)
	{
		arr[ size ] = valueIn;
		size++;
	}
	else
	{
		arr[ size ] = valueIn;
		size++;
		capacity += 5;
	}
		
}
void myVector::erase(int location)
{
	/*for( int i = 0; i < size; i++ )
	{
		if( arr[ i ] == location )
		{
			still haven't figure this out yet
		}
	}*/
}

void myVector::print()
{
	for( int i = 0; i < size; i++ ) 
		{
			cout << arr[i] << " ";
		}
}

int myVector::find(int valueIn)
{
	for( int i = 0; i < size; i++ )
	{
		if( arr[ i ] == valueIn )
			return valueIn;
	}
		return -1;
}
closed account (D80DSL3A)
This may work a bit better for push_back()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void myVector::push_back(int valueIn)
{	
	if( size == capacity)// a new larger array is needed
	{
                capacity += 5;// increase capacity
                int* temp = new int[capacity];// allocate a new larger array
                for(int i=0; i< size; ++i)
                     temp[i] = arr[i];// copy existing values to new array
                delete [] arr;// delete old array
                arr = temp;// assign new array to "permanent" pointer		
	}
        arr[ size ] = valueIn;// add the new value
	size++;		
}
Thanks a lot fun2code. I think I m getting this stuff. I have an erase function that I am struggling with. I think there is one thing I am missing but I can't get.

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
void myVector::erase(int location)
{
	for( int i = 0; i < size; i++ )
	{
		if( arr[ i ] == location )
		{
			int* temp = new int[ capacity-- ]; 
			size--;
			
                       // I think something has to go here to increment the pointer. Every time I 
                       // run the code it only deletes the last number in the array and not the location
                       // sent into the function
            
			for( int i = 0; i < size; i++ )
				temp[ i ] = arr[ i ];

			delete [] arr;
			arr = temp;
		}
	}
}

Example: The array prints out 2 4 6 8 10 12 14 16 18.
I need to delete the number 4, or 6, or etc, ( this is int location)  but it only deletes the 18.

Any thoughts?
Thanks again.

closed account (D80DSL3A)
Yes I have thoughts about it. I'm a bit confused. I'm going to assume that by "location" you mean "value". eg. the value stored in the 3rd element ( a location ) is 6. It seems fairly clear that this is what you mean.

If you wish to erase a value from the array simply copy all of the following values back one space.
There is no need to delete or new anything. The existing array can stay the same size. You even regain some excess capacity!

Since a given value may or may not exist in the array (eg. 22 does not so erase(22) would fail) the function should return a bool result to indicate success or failure.

Try this and let me know if it does what you need here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool myVector::erase(int value )
{
	int i=0;// start search at beginning of array
	while( arr[i] != value )// find index where value is stored.
	{
		++i;
		if( i == size )// entire array has been gone through
			return false;// value was not found
	}
	// value was found at element i - erase it	
	for(int j=i; j<size-1; j++)
		arr[j] = arr[j+1];// copy back one space
	size--;// reduce size by one	
	return true;
}


EDIT: If you don't follow the logic, please ask. I'm trying to help you understand this.
Last edited on
Thanks a lot fun2code. I think I understand it and it works. I learned more from your 29 lines of code than the hours of reading books and watching you tube. I really appreciate your time.

I noticed that you used the pre-increment operator in the while loop and a post- increment in the for loop is there any reason in particular as to why you did that?

Thanks again
^It wouldn't matter since there is no other use of the variable, so the pre/post increment would have the same effect.

Preincrement is faster if you don't modify the variable, but any decent compiler should be able to optimize it for you.

EDIT: Collary: Only if it is a basic type, if it is a user defined type it may not be depending on the complexity.
Last edited on
closed account (D80DSL3A)
firedraco is correct. The switching back and forth is due solely to inconsistent practice on my part.
I shall try to tighten that up (and use pre-increment where post-increment isn't needed).
Actually I should correct myself too...on basic types like int, it could be optimized, but on a user defined type it might not be.
Thanks gentlemen for all the help. I am sure you will be hearing from me again.
Topic archived. No new replies allowed.