如何在 C++ 中动态扩展数组?{就像在向量中} [英] How to expand an array dynamically in C++? {like in vector }
本文介绍了如何在 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屋!
查看全文