【问题标题】:is it possible to change the size of a dynamically created array using new operator是否可以使用 new 运算符更改动态创建的数组的大小
【发布时间】:2021-02-14 18:00:42
【问题描述】:

我们可以更改由new 运算符创建的数组的大小,就像使用reallocate() 完成的调整大小一样,如下所示?

在 C 中:

int *p = (int*)malloc(size_of(int));
reallocate(p,2*size_of(int));

如果不能,如何改变new操作符创建的数组的大小?

【问题讨论】:

  • 不,这是不可能的。在 C++ 中,std::vector 应该用于此目的。它在后台管理重新分配。
  • 有时std::vector 的再发明是学习练习的重点。虽然 STL 很好,应该继续使用,但有超过 2 年的遗留代码使用各种 newdelete 重新分配方案。查看类似问题First attempt at using new to dynamically create struct array, program hangs without error
  • 要重新分配的 C 函数名为 realloc,而不是 reallocate

标签: c++ dynamic


【解决方案1】:

您可以在此处使用newstd::copy/std::move

#include<iostream>
//              --> reference to a pointer
//              |
void resize(int*& begin, const int curr_size, const int size){
    int* temp = new int[size];
    int resize_val = std::min(curr_size, size);
    std::move(begin, begin+resize_val, temp);
    delete[] begin;
    begin = temp;
}

int main(){
   int* arr = new int[10];
   for(size_t i=0; i<10; ++i)arr[i]=15;
   resize(arr, 10, 20);
   for(size_t i=0; i<20; ++i)std::cout<<arr[i]<<" ";
   resize(arr, 20 , 5);
   for(size_t i=0; i<5; ++i)std::cout<<arr[i]<<" ";
   delete[] arr; // delete arr after use
}

输出:

15 15 15 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0
15 15 15 15 15

Demo in cpp.sh

【讨论】:

  • 当请求的大小小于当前大小时,您的调整大小(更具体地说是您的副本)不会考虑在内。在这种情况下,您将太多元素复制到新数组中。
  • @RemyLebeau 是的,同意。除了将大小调整为更小的尺寸之外,将copy 替换为move 是否会提高性能?
  • curr_size&lt;size?curr_size:size 可以替换为std::min(curr_size, size)。并且没有必要将temp 设置为nullptr,因为它会立即超出范围。至于性能,移动总是比副本更有效,或者至少同等有效,具体取决于被移动的类型。
【解决方案2】:

就像@Scheff 所说,在std::vector 的幕后分配新内存,如下示例代码:

int *c = new int[10]; // initial

delete[] c;
c = new int[20]; // after resizing

delete[] c; // gets called after after vector goes out of acope

【讨论】:

  • 您忘记了一个重要步骤 - 您需要在分配新数组之后和销毁旧数组之前将旧数组的内容复制/移动到新数组。
猜你喜欢
  • 2013-06-09
  • 1970-01-01
  • 2010-11-08
  • 2021-09-15
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
相关资源
最近更新 更多