C++: What is the proper way of resizing a dynamically allocated array?

后端 未结 4 787
谎友^
谎友^ 2021-01-03 01:59

In C, I would have done it using realloc.

In C++, one would normally consider using the STL vector class.

But how do I properly res

4条回答
  •  没有蜡笔的小新
    2021-01-03 02:20

    int* arr = new int[20];
    ...
    //wanna resize to 25?
    int* temp = new int[25];
    std::copy(arr, arr+20, temp);
    delete [] arr;
    arr = temp;
    ... //now arr has 25 elements
    

    But, of course, you shouldn't do this :)

提交回复
热议问题