如何动态地扩展在C ++中数组? {矢量像} [英] How to expand an array dynamically in C++? {like in vector }

查看:114
本文介绍了如何动态地扩展在C ++中数组? {矢量像}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说,我有

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

现在我想在第6元素添加到阵列中。我该怎么做呢?

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

推荐答案

您必须重新分配阵列中的数据复制:

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;

这篇关于如何动态地扩展在C ++中数组? {矢量像}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆