如何动态增加数组大小? [英] How to dynamically increase the array size?

查看:72
本文介绍了如何动态增加数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试制作一个添加2个大小不同的数组的程序.但是我想知道要动态增加阵列大小的容量吗?例如:array [4]然后将大小升级为2,以制作array [6] ;?没有使用向量

I've been trying to make a program that adds 2 arrays of different size. But I would like to know to to dynamically increase the array size capacity? Ex: array[4] then upgrade the size to 2 to make array[6];? WIthout using vectors

我尝试创建一个新的ptr,但是它不起作用.我收到错误消息:只读变量不可分配.

I tried creating a new ptr but it does not work. I get the error: Read only variable is not assignable.

int *ptr2 = new int[a2.size];


            // new ptr2 copies ptr1
            for (int i=0; i<(a1.size); i++) {
                ptr2[i] = a1.ptr[i];
            }


            // we want ptr1 to point to ptr2
            for (int i=0; i<(a2.size); i++) {
                ptr2[i] += a2.ptr[i];
            }

            delete [] a1.ptr;

            a1.ptr=ptr2;

推荐答案

您不能更改数组的大小,但不必更改.您可以分配一个更大的新数组,复制要保留的值,删除原始数组,然后更改成员变量以指向新数组.

You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array.

  1. 分配一个新的[]数组,并将其存储在一个临时指针中.

  1. Allocate a new[] array and store it in a temporary pointer.

复制要保留的先前值.

删除[]旧数组.

更改成员变量 ptr size 以指向新数组并保持新大小.

Change the member variables, ptr and size to point to the new array and hold the new size.

这篇关于如何动态增加数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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