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

问题描述

我目前正在用C ++创建向量类,并且正在尝试一些东西。我不确定是否可以做到这一点而不会导致内存泄漏或遗留内存并且无法正确删除它。我已经评论了我有疑问的代码行。任何帮助将不胜感激,谢谢您!

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...