C++ PushBack/PushFront methods

I'm trying to implement a PutFront method that places an integer at the FRONT of an array. So for example:

array before PutFront(1):
5
10
15
array after PutFront(1):
1
5
10
15

I've already created a PutBack method that puts an integer at the back of an array like this: (this is all in a source file, my main file will test these functions)

size_t xArray::PutBack(const int c){
if ( len == size ) {
int* temp = data;
size = size * 2;
data = new int[size];
for ( size_t i = 0; i < len; i++ ) {
data[i] = temp[i];
}
delete[] temp;
data[len] = c;
}
else {
data[len] = c;
}
return len = len+1;
}

I'm thinking that the PutFront method should be somewhat similar to the PutBack method. Can someone please help me create PutFront. This is all I have:(there is a header file with these private variables:

private:
size_t len;
size_t size;

//data of int array
int* data;
int* start;

size_t xArray::PushFront(const int c){
int* temp = data;
size = size * 2;
data = new int[size];
for ( size_t i = size; i < len; i++ ) {
data[i] = temp[i];
}
delete[] temp;
data[len] = c;
}

Comments

  • Copy the value into the first item of new array, then copy index i from the old array to index i+1 in the new array.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion