如何从自定义矢量中删除某些内容? C++

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

我目前正在用 C++ 制作矢量 class,我只是在尝试一些东西。我不确定这是否可以在不导致内存泄漏或留下内存而不正确删除它的情况下完成。我已经评论了我有疑问的代码行。任何帮助将不胜感激,提前致谢!

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--;
}

我没有重新定位,而是将其更改为执行此操作,它工作得更好并且优化得更好。

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--;
}