【问题标题】:How to Copy Data from One Array to Another Without Names? (C++)如何在没有名称的情况下将数据从一个数组复制到另一个数组? (C++)
【发布时间】: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)];,这样您就有了新数组的名称

标签: c++ arrays dynamic naming


【解决方案1】:
array_list::growList(int increase = GROW_FACTOR)
{
    unsigned int* temp = m_storage;
    m_storage = new unsigned int[m_capacity * increase];
    for (int i = 0; i < m_capacity; i++)
        m_storage[i] = temp[i];
    m_capacity *= increase;
    delete temp;    
}

我不知道您是否要更改其他变量,但这基本上应该按照您的要求进行。

【讨论】:

  • 分配到临时然后移动以产生更好的异常/提前退出安全。就目前而言,如果new 抛出,容量与指针的容量不一致。
  • 这太好了,谢谢。我无法完全理解指针的使用,这正是我需要让我走上正轨的!
  • @Yakk 这是一个很好的观点,但我觉得如果 new 抛出该程序无论如何都打算退出。不过我会改的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
  • 2015-10-18
  • 2022-01-14
  • 2014-08-24
  • 1970-01-01
  • 2012-04-08
相关资源
最近更新 更多