C ++,我需要能够调整动态数组的大小

时间:2019-02-04 03:59:49

标签: c++

我有这个动态数组的代码,我是在实验中上交的。我的老师回答说“甚至不会编译,也不会调整数组的大小”。我在处理“不调整数组大小”的注释时遇到麻烦,这意味着我必须添加调整数组大小的功能。请快速帮助! (它确实可以编译)。赞赏。

我应该编写一个程序,要求用户初始调整数组大小。根据该大小创建一个数组,要求输入数字,然后插入数字。然后重复获取并插入一个数字,根据需要调整数组的大小,或者直到输入数字-1为止。 打印列表。

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    int count;
    cout << "How many values do you want to store in your array?" << endl;
    cin >> count;
    int* DynamicArray;
    DynamicArray = new int[count];

    for (int i = 0; i < count; i++) {
        cout << "Please input Values: " << endl;
        cin >> DynamicArray[i];

        {
            if (DynamicArray[i] == -1) {
                delete[] DynamicArray;
                cout << "The program has ended" << endl;
                exit(0);
            }
            else {
                cout << endl;
            }
        }
    }
    for (int k = 0; k < count; k++) {
        cout << DynamicArray[k] << endl;
    }

    delete[] DynamicArray;
    return 0;
}

1 个答案:

答案 0 :(得分:1)

当阵列已满时,我们需要调整其大小。这是我的解决方法

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

int main()
{
    int count;
    cout << "How many values do you want to store in your array?" << endl;
    cin >> count;
    if (count <= 0) {
        cout << "The value should be greater than zero" << endl;
        exit(0);
    }
    int* DynamicArray;
    DynamicArray = new int[count];

    int i = 0, value = 0;
    while (1) {
        cout << "Please input Values: " << endl;
        cin >> value;

        if (value == -1) {
                cout << "The program has ended" << endl;
                break;
        }
        else if (i < count)
        {
            DynamicArray[i++] = value;
        }
        else
        {
            // resize the array with double the old one
            count = count * 2;
            int *newArray = new int[count];
            memcpy(newArray, DynamicArray, count * sizeof(int));
            delete[]DynamicArray;
            newArray[i++] = value;
            DynamicArray = newArray;
        }
    }
    for (int k = 0; k < i; k++) {
        cout << DynamicArray[k] << endl;
    }

    delete[] DynamicArray;
    return 0;
}