【问题标题】:Appending to an array in Dynamic Memory附加到动态内存中的数组
【发布时间】:2017-10-09 21:01:59
【问题描述】:

使用动态内存,我正在尝试创建一个将数字存储在动态数组中的类(因此 123 将是 arr[0] = 1,arr[1] = 2,arr[2] = 3)并且能够追加数字(例如,如果存储的数字是 123,您可以添加更多数字.. 45,新数字将是 12345)。

到目前为止,这是我的代码:我将如何制作附加函数?

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    int *exampleArray; //new array into exsistence 

    exampleArray = new int[5]; // dynamically allocates an array of 5 ints
    for (int i = 1; i < 5; i++)
    {
        exampleArray[i] = i;
        cout << exampleArray[i] << endl;
    }

    delete exampleArray; // deleted from exsistence

    system("pause"); // to show the output
    return 0;
}

【问题讨论】:

  • 追加”是什么意思?您打算在哪里添加数字?考虑检查当前分配的大小是否足够并调整大小+复制数组。甚至更好 - 使用 std::vector&lt;int&gt; 而不是动态的 int 数组
  • 你也必须delete [] what you new []
  • 不能保证额外的内存分配会在原始数组的末尾分配内存。
  • 使用std::vector&lt;int&gt;怎么样??
  • 对数组进行扩展或追加的过程,是1)动态分配一个new更大的数组; 2) 将旧元素复制到新数组中; 3)删除旧数组。我们中的许多人更喜欢使用std::vector,它为我们做这件事。

标签: c++ arrays dynamic-memory-allocation


【解决方案1】:

如果您使用new[] 分配一个数组,“追加”到它的唯一方法是new[] 一个更大的新数组,将旧数组中的现有值复制到其中,然后delete[] (不是delete)旧数组并更新您的数组指针以指向新数组。

另外,请注意数组是从 0 开始索引的。您的循环没有用任何数据填充exampleArray[0]

例如:

int *arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;

...

int *newarr = new int[5];
std::copy(arr, arr+3, newarr);
newarr[3] = 4;
newarr[4] = 5;
delete[] arr;
arr = newarr;

...

delete[] arr;

您可以通过预先分配比实际需要更多的内存来稍微优化这一点,并且只有在实际超过该内存时才“增长”。例如:

int *arr = NULL;
int num = 0, cap = 0;

void append(int digit)
{
    if (num == cap)
    {
        int *newarr = new int[cap + 10];
        std::copy(arr, arr+num, newarr);
        delete[] arr;
        arr = newarr;
        cap += 10;
    }

    arr[num] = digit;
    ++num;
}

...

append(1);
append(2);
append(3);

...

append(4);
append(5);

...

delete[] arr;

话虽如此,您所要求的最好使用std:vector 来处理。它是一个动态长度的容器,可以为您处理这些丑陋的细节。

例如:

std::vector<int> arr;

void append(int digit)
{
    arr.push_back(digit);
}

...

append(1);
append(2);
append(3);

...

append(4);
append(5);

...

【讨论】:

  • 您应该保留重点或将std::vector 部分移到答案更突出的部分。
  • @user0042:我的回答,我的选择,不是你的。在提供更好的建议之前,我更愿意向人们解释在他们显示的代码范围内事情是如何工作的。
  • @Remy 够公平的!
【解决方案2】:

不需要您使用std::vector 容器或任何其他指针的替代解决方案是使用cstdlib C++ 标头中的malloc()/realloc()/free() 系列函数,如下所示:

int *exampleArray;
exampleArray = (int *) malloc(5 * sizeof(int));
for (int i = 1; i < 5; i++)
{
   exampleArray[i] = i;
   cout << exampleArray[i] << endl;
}
// Now to add further elements
exampleArray = (int *) realloc(7 * sizeof(int)); // Added space for 2 new elements
for (int i = 5; i < 7; i++) {
   exampleArray[i] = i;
   cout << exampleArray[i] << endl;
}
free(exampleArray);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2020-05-03
    相关资源
    最近更新 更多