Help with push_front

My push_front function is suppose to push data into the front of the array

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
 bool UniqueVector<T>::push_front(const T& data){

	//If data is already in the array, return false
	for(int index=0; index < arraySize; index++){
		if(array[index] == data)
			return false;
	}
	//made temp, double capacity, copy elements from array to temp
	// deallocated array and pointed array to temp
	if(arraySize == arrayCapacity){
		arrayCapacity*=2;
		T* temp = new T[arrayCapacity];
		for(int index=0; index<arraySize; index++)
			temp[index] = array[index];
		delete [] array;
		array = temp;
	}
        arraySize++;
        //Shift the elements of the array to the right
	for(int index=arraySize-1; index>0; index=index-1)
            	array[index] = array[index-1];

	array[0] = data;
	return true;

	if(arraySize==0){
		array[0] = data;
		arraySize++;
		return true;	
	}	


using the my at function to place data into the front.
1
2
3
4
5
6
7
8
9
10
11
12
template<typename T>
bool UniqueVector<T>::at(unsigned int pos, T& data){
	if(pos < arraySize){
		//if there's nothing in the position
		if(array[pos] == NULL){
			return false;
		}
		data = array[pos];
		return true;
	}
	return false;
}


My problem when I try to test the code, when push_front is false, at would still add elements into the front of the array. Any help or insight would be appreciated.
Last edited on
My problem when I try to test the code, when push_front is false, at would still add elements into the front of the array.


at does not add data to the array. Ever. So your description of the problem seems to be inaccurate. What code are you attempting to test?
1
2
3
REQUIRE( testVector.push_front(0) == false);
	testVector.at(0,temp);
	REQUIRE( temp == 2);


I apologize, but I'm having a hard time debugging this code. When ( testVector.push_front(0) == false); the program is not supposed to push 0 to the front of the array. Temp in this case would still be 2, since the test code
1
2
3
REQUIRE( testVector.push_front(2) == true );
	testVector.at(0,temp);
	REQUIRE( temp == 2 );
pushed 2 in the front.

When I compile and tried to run the test case, it fails with because it pushed 0 into the front. I occasionally get a malloc error saying that position being freed is not allocated.
The only obvious thing I see wrong is lines 5-7 in your at snippet which should be entirely removed, but I don't see how it would have the effect you describe. There is source code not presented here that is probably responsible for what you're seeing.

Have you implemented a proper copy constructor and copy assignment operator for your UniqueVector type?

Topic archived. No new replies allowed.