c++ - 满时分配一个新数组?

标签 c++

我的任务是获取一个对象的数组(在我的代码中为 arr),当它已满时,分配一个两倍大小的新数组,并用 arr< 填充它的内容,最后删除arr

我尝试了几种不同的方法来实现这一点,但每种方法都给我一个糟糕的内存分配错误。当考虑 arr 是对象的一部分并且新分配的数组也必须是对象的一部分时,我被挂断了。代码片段在我的对象的一个​​函数中。

if(num_elements == max){
    int *temp_arr = new int[max];
    copy(arr,arr + max,temp_arr);
    delete [] arr;
    arr = new int[2*max];
    copy(temp_arr,temp_arr + max,arr);
    max *=2;
    delete [] temp_arr;
}

最佳答案

您正在制作两个单独的拷贝,而只需要一个拷贝,就像您的说明告诉您的那样。

试试这个:

if (num_elements == max){
    int temp_max = max * 2;
    int *temp_arr = new int[temp_max];
    copy(arr, arr + num_elements, temp_arr);
    delete [] arr;
    arr = temp_arr;
    max = temp_max;
}

关于c++ - 满时分配一个新数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58066261/

相关文章:

c++ - 使用 sscanf 读取字符串

c++ - 整个应用程序的变量

c++ - 在 QQuickItem 上打开 QFileDialog

c++ - 关闭 session 后 Tensorflow C++ 不释放 GPU 资源

c++ - 在 C++ 服务器中提供图像

c++ - 如何访问另一个本地的本地变量?

c++ - 错误 : variable or field ‘myfunction’ declared void

C++ 结构运算符 : conversion from to non-scalar type requested

c++ - 当算术运算溢出时,它们会产生确定性数字吗?

c++ - 如何返回不可用的 const 引用