How to resize array in C++?

前端 未结 6 565
感情败类
感情败类 2020-11-29 09:16

I need to do the equivalent of the following C# code in C++

Array.Resize(ref A, A.Length - 1);

How to achieve this in C++?

6条回答
  •  -上瘾入骨i
    2020-11-29 09:49

    You cannot resize array, you can only allocate new one (with a bigger size) and copy old array's contents. If you don't want to use std::vector (for some reason) here is the code to it:

    int size = 10;
    int* arr = new int[size];
    
    void resize() {
        size_t newSize = size * 2;
        int* newArr = new int[newSize];
    
        memcpy( newArr, arr, size * sizeof(int) );
    
        size = newSize;
        delete [] arr;
        arr = newArr;
    }
    

    code is from here http://www.cplusplus.com/forum/general/11111/.

提交回复
热议问题