Search code examples
c++vectorpush-backcapacity

Increase capacity for vector


Disclaimer 1 - I'm new to programming Disclaimer 2 - I have searched and searched, but can't find the help I'm looking for.

For a project, I am more or less re-writing the vector class in a more stripped down form. The part I'm hung up with is writing the push_back method. All's well until I have to increase the capacity of the array.

I assume what should be done is create a new vector with the increased size, and then copy the elements from the old vector to the new one, then use the assignment operator to assign oldVector to newVector.

I have either written my push_back method incorrectly, overloaded the = operator incorrectly, or else I'm just lacking in my understanding on what should be happening. Any help would be greatly appreciated.

When compiling, I get the error "lvalue required as left operand of assignment" on the line where I assign this = tempV

template <class T>
Vector<T>& Vector<T>::operator = (const Vector<T> & v)
{
    int newSize = v.size();
    int newCapacity = v.getCapacity();
    data = new T[newCapacity];
    for(int i = 0; i < newSize; i++)
        data[i] = v.data[i];
    return *this;
}

template <class T>
void Vector <T> :: push_back(const T & number)
{
    if(numItems == capacity)
    {
        Vector <T> tempV(this->capacity * 2);
        for(int i = 0; i < numItems; i++)
            tempV.data[i] = data[i];
        *this = tempV;
    }
    if(numItems < capacity)
        data[numItems++] = number;
}

UPDATE So I see why my code wouldn't compile while using

*this = tempV;

in my copy method, I was using v.size and not v.size() as a method. After fixing that, the code compiles and runs, however the capacity of my vector is the same and did not increase as I was expecting. I'm still missing something. The code above has been updated.

Thanks again for any/all help!


Solution

  • Why do you have to create a new Vector<T>? Just create a new array:

    template <class T>
    void Vector <T> :: push_back(const T & number)
    {
        if(numItems == capacity)
        {
            capacity *= 2;
            T* newData = new T[capacity];
            std::copy(data, data + numItems, newData);
            delete[] data;
            data = newData;
        }
    
        data[numItems++] = number;
    }