【发布时间】:2014-10-13 21:41:37
【问题描述】:
我现在正在处理一项任务,但遇到了障碍。赋值是 C++ 中的一个数组列表,每次用完存储新元素的空间时动态扩展 2 倍(最初从 2 个元素的空间开始)。这是我正在处理的代码(其中一些包含在教授提供的单独 .h 文件中,为了保持简洁,我不会发布所有内容)。
#include "array_list.h"
//initial size to create storage array
static const unsigned int INIT_SIZE = 2;
//factor to increase storage by when it gets too small
static const unsigned int GROW_FACTOR = 2;
unsigned int growthTracker = 1;
array_list::array_list()
{
m_storage = new unsigned int[INIT_SIZE];
m_capacity = INIT_SIZE;
m_current = -1;
m_size = 0;
}
array_list::~array_list()
{
delete m_storage;
}
void array_list::clear()
{
delete m_storage;
m_storage = new unsigned int[INIT_SIZE];
m_capacity = INIT_SIZE;
m_current = -1;
m_size = 0;
}
unsigned int array_list::size() const
{
return m_size;
}
bool array_list::empty() const
{
bool A = 0;
if(m_size == 0)
{
A = 1;
}
return A;
}
void array_list::insert(const unsigned int val)
{
m_storage[m_size++] = val;
m_current = m_size;
}
void array_list::grow_and_copy()
{
if(m_size == m_capacity)
{
new unsigned int[INIT_SIZE * (GROW_FACTOR ^ growthTracker)];
growthTracker++;
m_capacity = m_capacity * 2;
}
m_storage[m_size++] = val;
}
现在,我的问题是试图弄清楚如何将旧的较小数组的值复制到新的较大的数组中。如果我不使用动态未命名数组,这将很容易通过循环来实现,即“对于某个范围,arrayA[i] = arrayB[i]”的简单案例。但是,因为数组只是被定义为新的 unsigned int[],我不知道该怎么做。没有名称,所以我不知道如何告诉 C++ 将哪个数组复制到哪个数组中。而且由于可以多次调用grow_and_copy,我很确定我不能给它们起名字,对吧?因为那样我最终会得到多个同名的数组。谁能在这里指出我正确的方向?非常感谢。
【问题讨论】:
-
m_storage 必须在某处声明,但我没有找到它。它可能在您的
array_List.h文件中 -
但是看看
m_storage是如何被实例化的。m_storage = new unsigned int[INIT_SIZE];new关键字返回你的数组,你必须将它分配给一个变量 -
如果你已经在你的
.h文件中声明了m_storage(大概是unsigned int*),只需让你的增长函数声明一个unsigned int*类型的临时变量并分配给它一个指向新数组的指针,从m_storage复制到新数组中,删除m_storage,然后将temp分配给m_storage。这是假设您没有使用 C++11 智能指针,当然 -
我会澄清:是的,m_storage 在 .h 文件中声明为 unsigned int * 。
-
好的,所以不要使用
new unsigned int[INIT_SIZE*(GROW_FACTOR^growthTracker)];,而是使用unsigned int* newArray = new new unsigned int[INIT_SIZE*(GROW_FACTOR^growthTracker)];,这样您就有了新数组的名称