![](/img/trans.png)
[英]How to create a reference to an array created dynamically using new operator in C++?
[英]is it possible to change the size of a dynamically created array using new operator
我們可以更改由new
運算符創建的數組的大小,例如使用reallocate()
完成的調整大小,如下所示?
在 C 中:
int *p = (int*)malloc(size_of(int));
reallocate(p,2*size_of(int));
如果不可能,如何更改new
運算符創建的數組的大小?
您可以在此處將new
與std::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
}
Output:
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
就像@Scheff 所說,在std::vector
new memory 的引擎蓋下,分配如下示例代碼:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.