Search code examples
c++arraysclasspointersdynamic-memory-allocation

Creating a custom vector class. Push_back function only working for the first value


In my Comp Sci class, we are learning how to make our own vector class. We will eventually store our custom made string class objects in a custom made vector class. I wanted to try and build a vector class of integers beforehand for simplicity.

So far, I have a default constructor that initializes my pointer to an empty array and sets the size to 0. Then I try to append some values using my push_back function and then check to make sure it was done correctly.

When I do std::cout << v[0] << std::endl;

I get the correct output (10). However, if I call push_back again and then call v[1] I get 0.

I feel like I am not allocating memory correctly in my push_back function but I am not sure.

Thanks for any advice!

[part 1][1]

[part 2][2]

sorry if my formatting is wrong I am new to posting here.

class:

class myVector
{
private:
    int *data; //will point to an array of ints
    size_t size; //determins the size of array
public:
    myVector(); // default constructor
    void push_back(int); // appends an integer to the vector
    int operator[](size_t);
    size_t sizeOf();
};

main:

int main()
{
    myVector v;
    v.push_back(10);
    std::cout << v.sizeOf() << std::endl;
    v.push_back(14);
    std::cout << v.sizeOf() << std::endl;
    std::cout << v[1] << std::endl;

    return 0;

}

member functions:

size_t myVector::sizeOf()
{
    return size;
}

int myVector::operator[](size_t location)
{
    return this->data[location]; //this will return the value at data + 
                                 //location
}

myVector::myVector()
{
    this->data = new int[0]; //initialize the data to an empty array of 
                             //ints
    size = 0; //initialize the size to 0
}

void myVector::push_back(int val)
{
    if(size == 0) //if size == 0, create a new array with 1 extra index
    {
        ++size;
        delete [] this->data;
        this->data = new int[size];
        this->data[0] = val;
    }
    else
    {
         ++size;
         int *temp = new int[size - 1];
         for(int i = 0; i != (size - 1); i++)
         {
              temp[i] = this->data[i];
         }
         delete [] this->data;
         this->data = new int[size];
         for(int i = 0; i != (size - 1); i++)
         {
             this->data[i] = temp[i];
         }
         this->data[size] = val;
         delete [] temp;
    }
}

Solution

  • In your code:

    this->data[size] = val;
    

    you are going outside of the allocated array.

    Same in the previous loop (in its last iteration):

     for(int i = 0; i != (size - 1); i++)
     {
         this->data[i] = temp[i];
     }