【问题标题】:How to remove something from a custom vector? C++如何从自定义向量中删除某些内容? C++
【发布时间】:2020-12-03 11:55:08
【问题描述】:

我目前正在用 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--;
}

【问题讨论】:

  • maxsizeconst 吗?
  • 请提供minimal reproducible example。什么是数组?什么是T? tmp[x] = array[i]; 会扔吗?
  • 我看到的一个问题是 toRemoveunsigned int 但您使用 int i 进行迭代。另一个问题是,如果代码中存在异常,例如 array 包含非平凡对象并且 tmp[x] = array[i]; 抛出异常,您可能会泄漏。
  • 不用说,以临时方式创建自己的矢量类并不能很好地工作。最好获取有关其完成方式的示例并进行研究。
  • 旁注:删除元素时调整数据存储的大小是昂贵的。只需将后面的元素移过来以覆盖孔并将大小减小 1。稍后您可能会再次需要内存,所以最好保留它。

标签: c++ arrays memory vector erase


【解决方案1】:

我没有重新分配,而是改为这样做,它工作得更好,优化得更好。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    相关资源
    最近更新 更多