How to expand an array dynamically in C++? {like in vector }

后端 未结 5 1308
有刺的猬
有刺的猬 2020-12-01 10:01

Lets say, i have

int *p;
p = new int[5];
for(int i=0;i<5;i++)
   *(p+i)=i;

Now I want to add a 6th element to the array. How do I do it

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 10:34

    You have to reallocate the array and copy the data:

    int *p;
    p = new int[5];
    for(int i=0;i<5;i++)
       *(p+i)=i;
    
    // realloc
    int* temp = new int[6];
    std::copy(p, p + 5, temp); // Suggested by comments from Nick and Bojan
    delete [] p;
    p = temp;
    

提交回复
热议问题