Search code examples
c++arraysmemoryvectorerase

How to remove something from a custom vector? C++


I am currently making a vector class in C++ and am just trying some stuff out. I am not sure if this can be done without causing a memory leak or leaving memory behind and not deleting it properly. I have commented the lines of code that I have questions for. Any help will be appreciated, thank you in advance!

void remove(unsigned int toRemove) 
{
    T* tmp = new T[maxsize];    // T is the datatype of the vector
    int x = 0;
    for (int i = 0; i < size; i++)
    {
        if (i != toRemove)
        {
            tmp[x] = array[i];  // does this line cause memory leak ?
        }
        else 
        {
            x--;
        }
        x++;
    }

    delete[] array;     // is there anything else I need to delete?
    array = tmp;
    size--;
}

Solution

  • Instead of realocating I changed it to do this and it works better and is better optimised.

    void remove(unsigned int toRemove) 
    {
        unsigned int x = 0;
        for (unsigned int i = 0; i < size; i++)
        {
            if (i != toRemove)
            {
                array[x] = array[i]; // shifts the elements backwards 
            }
            else 
            {
                x--;
            }
            x++;
        }
        size--;
    }