更改数组大小C ++ [英] Change array size C++

查看:130
本文介绍了更改数组大小C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个数组指针作为这样的全局变量:

I have created an array pointer as a global variable like this:

T *bag;
        bag = new T[size];

我有一个方法,可以将东西插入到数组中.但是,如果它检测到它将使数组溢出,则需要调整数组的大小(不包含向量).我一直在阅读有关整个堆栈溢出的问题,但答案似乎并不适用于我,因为我需要将旧数组中的数据复制到新数组中.另外,如果我在方法内部创建一个更大的新数组,然后将数据复制到新数组中,一旦方法结束,该数组将消失,但是我需要再次将其作为全局变量,所以我所有的方法可以看到...我应该如何进行? 谢谢

I have a method where I insert things into the array; however, if it detects that it will overflow the array, I need to resize the array (without vectors). I've been reading about this question all over stack overflow but the answers don't seem to apply to me because I need the data from the old array copied into the new array. Additionally, if I create a new array of a larger size inside the method and then copy the data over to the new array, once the method ends, the array will disappear, but I need it to be a global variable again so all my methods can see it...How should I proceed? Thank you

推荐答案

要调整数组大小,您必须分配一个新数组并将旧元素复制到新数组中,然后删除旧数组.

To resize an array you have to allocate a new array and copy the old elements to the new array, then delete the old array.

T * p_bag;
p_bag = new T[old_size];
//...
T * p_expanded_bag = new T[new_size];
for (unsigned int i = 0; i < old_size; ++i)
{
  p_expanded_bag[i] = p_bag[i];
}
delete[] p_bag;
p_bag = p_expanded_bag;

您可以使用std::copy而不是for循环.

You could use std::copy instead of the for loop.

这篇关于更改数组大小C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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