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

C++ I need to be able to resize my dynamic array

本文关键字:数组 动态 调整 C++      更新时间:2023-10-16

我有一个动态数组的代码,我把它交给了实验室。我的导师回答说"甚至不会编译,不会调整数组的大小"。我在处理"不调整数组大小"的评论时遇到问题,这意味着我必须添加调整数组大小的功能。请赶紧帮忙!(它确实编译(。欣赏它。

我应该制作一个程序,要求用户最初调整数组的大小。根据该大小创建一个数组,要求输入数字,然后插入该数字。然后重复获取并插入一个数字,根据需要调整数组大小,或者直到他们输入 -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;
}

当数组已满时,我们需要调整它的大小。这是我的解决方案

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