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

后端 未结 5 1294
有刺的猬
有刺的猬 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:25

    Same as others are saying, but if you're resizing the array often, one strategy is to resize the array each time by doubling the size. There's an expense to constantly creating new and destroying old, so the doubling theory tries to mitigate this problem by ensuring that there's sufficient room for future elements as well.

提交回复
热议问题