没有向量,指针的C ++在运行时增加数组大小 [英] Increase array size at runtime in c++ without vector, pointer

查看:87
本文介绍了没有向量,指针的C ++在运行时增加数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在c ++中声明了一个int数组,它的大小是一定的. 例如int a [6]

I have declared a array of int in c++ with some size. say, int a[6]

在运行时,如果我的数组大小超过6,则需要增加它.

at runtime if my array size exceeds 6, then i need to increase it.

我将不会使用指针,向量,并且大小不会由用户给出.

i am not going to use pointer, vector and the size will not be given by the user.

推荐答案

您无法在运行时更改数组的大小.一种替代方法是创建一个比现有数组大的新数组.将现有数组的元素复制到新数组,然后删除现有数组.并更改成员变量,ptr和大小.

You can not change the size of your array at run time. An alternative is to create a new array which is larger than the existing one. Copy the elements of the existing array to the new array and delete the existing array. And Change the member variables, ptr and size.

类似这样的东西:

int* newArray = new int[sizeOfArray];
std::copy(oldArray, oldArray + std::min(sizeofOldArray, sizeOfArray), newArray);
delete[] oldArray;
oldArray = newArray;

最好是使用 std :: vector

这篇关于没有向量,指针的C ++在运行时增加数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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