如何在没有名称的情况下将数据从一个数组复制到另一个数组?(C++)

How to Copy Data from One Array to Another Without Names? (C++)

本文关键字:数组 一个 复制 C++ 另一个 情况下 有名称 数据      更新时间:2023-10-16

我现在正在做一项任务,遇到了障碍。赋值是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]"的例子。然而,因为数组只是被定义为新的无符号int[],我不知道该怎么做。没有名称,所以我不知道如何告诉C++将哪个数组复制到哪个数组中。既然growt_And_copy可以被调用多次,我很确定我不能给它们起名字,对吧?因为那样的话,我会得到多个具有相同名称的数组。有人能给我指正确的方向吗?非常感谢。

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;    
}

我不知道你是否还想改变其他变量,但这基本上应该符合你的要求。

相关文章: